Skip to content

Commit b7d5e1f

Browse files
committed
fix: buffer offset overflow
1 parent 03c795d commit b7d5e1f

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

esp-hal/src/dma/buffers.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1527,8 +1527,12 @@ impl DmaTxStreamBufView {
15271527
/// Pushes a buffer into the stream buffer.
15281528
/// Returns the number of bytes pushed.
15291529
pub fn push(&mut self, buf: &[u8]) -> usize {
1530-
let bytes_to_fill = buf.len().min(self.available_bytes());
1530+
let bytes = self.available_bytes();
1531+
let bytes_to_fill = buf.len().min(bytes);
15311532
let buf = &buf[..bytes_to_fill];
1533+
if buf.is_empty() {
1534+
return 0;
1535+
}
15321536

15331537
fn truncate_by(n: usize, by: usize) -> usize {
15341538
(n >= by).then_some(n - by).unwrap_or(n)
@@ -1540,29 +1544,28 @@ impl DmaTxStreamBufView {
15401544
let dma_start = self.descriptor_idx * chunk_size + self.descriptor_offset;
15411545
let dma_end = truncate_by(dma_start + buf.len(), dma_size);
15421546

1543-
if dma_start <= dma_end {
1547+
if dma_start < dma_end {
15441548
self.buf.buffer[dma_start..dma_end].copy_from_slice(buf);
15451549
} else {
15461550
self.buf.buffer[dma_start..].copy_from_slice(&buf[..dma_size - dma_start]);
15471551
self.buf.buffer[..dma_end].copy_from_slice(&buf[dma_size - dma_start..]);
15481552
}
15491553

15501554
let descs = (self.descriptor_idx..n_chunks).chain(0..self.descriptor_idx);
1551-
let mut offset = self.descriptor_offset;
15521555
let mut bytes_filled = 0;
15531556

15541557
for d in descs {
15551558
let desc = &mut self.buf.descriptors[d];
1556-
let bytes_in_d = desc.size() - offset;
1559+
let bytes_in_d = desc.size() - self.descriptor_offset;
15571560
if bytes_in_d + bytes_filled > buf.len() {
15581561
// I will have empty space in `desc`
15591562
self.descriptor_idx = d;
1560-
self.descriptor_offset = offset + buf.len() - bytes_filled;
1563+
self.descriptor_offset = self.descriptor_offset + buf.len() - bytes_filled;
15611564
break;
15621565
}
15631566
// fill `desc` with data from `buf`
15641567
bytes_filled += bytes_in_d;
1565-
offset = 0;
1568+
self.descriptor_offset = 0;
15661569

15671570
desc.set_owner(Owner::Dma);
15681571
desc.set_length(desc.size());

0 commit comments

Comments
 (0)