From 4157a58a4c29fece6c9061d9a6db7fd2ad408dca Mon Sep 17 00:00:00 2001 From: "Daniel van Ham Colchete (aka vham)" Date: Wed, 30 Oct 2024 00:17:27 -0400 Subject: [PATCH] i2c_slave.c: fix buffer overrun on s_i2c_handle_complete() Fixing a buffer overrun of i2c_slave->data_buf. The i2c_ll_read_rxfifo function was using t->rcv_fifo_cnf (the I2C slave reading code's buffer size) as the limit for how many bytes on write on i2c_slave->data_buf. This buffer size for i2c_slave->data_buf is generally smaller than the buffer that the I2C slave reading code has. --- components/esp_driver_i2c/i2c_slave.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/components/esp_driver_i2c/i2c_slave.c b/components/esp_driver_i2c/i2c_slave.c index b5f16fb9fc0..4efa0da4186 100644 --- a/components/esp_driver_i2c/i2c_slave.c +++ b/components/esp_driver_i2c/i2c_slave.c @@ -72,11 +72,12 @@ static IRAM_ATTR void s_i2c_handle_complete(i2c_slave_dev_handle_t i2c_slave, i2 i2c_hal_context_t *hal = &i2c_slave->base->hal; uint32_t rx_fifo_cnt; i2c_ll_get_rxfifo_cnt(hal->dev, &rx_fifo_cnt); + uint32_t fifo_cnt_rd = MIN(t->rcv_fifo_cnt, rx_fifo_cnt); if (rx_fifo_cnt != 0) { - i2c_ll_read_rxfifo(hal->dev, i2c_slave->data_buf, t->rcv_fifo_cnt); - memcpy(t->buffer + i2c_slave->already_receive_len, i2c_slave->data_buf, t->rcv_fifo_cnt); - i2c_slave->already_receive_len += t->rcv_fifo_cnt; - t->rcv_fifo_cnt -= t->rcv_fifo_cnt; + i2c_ll_read_rxfifo(hal->dev, i2c_slave->data_buf, fifo_cnt_rd); + memcpy(t->buffer + i2c_slave->already_receive_len, i2c_slave->data_buf, fifo_cnt_rd); + i2c_slave->already_receive_len += fifo_cnt_rd; + t->rcv_fifo_cnt -= fifo_cnt_rd; } if (i2c_slave->callbacks.on_recv_done) {