ASoC: SOF: ipc4-mtrace: fix the wrapped read when the user buffer is short
Subsystems (3)
PATCH 1/1 ASoC: SOF: ipc4-mtrace: fix the wrapped read when the user buffer is short
From: Suyuan Wang <[email protected]>
When the log data wraps around the end of the slot, sof_ipc4_mtrace_dfs_read() copies it in two parts:
sof_mailbox_read(..., log_buffer, avail - write_ptr); sof_mailbox_read(..., log_buffer + avail - write_ptr, write_ptr);
This assumes that avail is still the full distance from read_ptr to write_ptr. But avail has just been cut down to count - sizeof(avail) if the user asked for less. If it ends up smaller than write_ptr, avail - write_ptr wraps around, and the first sof_mailbox_read() gets a length of about 4 GiB for the 4 KiB log_buffer.
For example, with read_ptr = 4080 and write_ptr = 16, a read of 12 bytes gives avail = 8 and a copy of 0xfffffff8 bytes. If avail is cut but still larger than write_ptr, the two parts don't line up with read_ptr and the user gets the wrong bytes.
Copy from read_ptr up to the end of the slot, but no more than avail, and take the rest from the start of the slot.
Found with a static analysis tool and checked by hand.
---
Compile tested (x86_64, W=1). I don't have SOF hardware, so I checked the pointer arithmetic in userspace instead: the code of this function with the mailbox replaced by an array, under ASan. Without the patch a 12-byte read at read_ptr 4080, write_ptr 16 copies 0xfffffff8 bytes, and a 104-byte read at read_ptr 4000 returns 16 wrong bytes; with it both return the expected data.
--- sound/soc/sof/ipc4-mtrace.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-)
sound/soc/sof/ipc4-mtrace.c +8 -5
@@ -230,14 +230,17 @@ static ssize_t sof_ipc4_mtrace_dfs_read(struct file *file, char __user *buffer,/* Read data between read pointer and write pointer */ sof_mailbox_read (sdev, log_buffer_offset + read_ptr, log_buffer, avail); }else { +/* avail may have been cut to the user's count above */ +u32 tail =min (avail, log_buffer_size - read_ptr); +/* read from read pointer to end of the slot */ sof_mailbox_read (sdev, log_buffer_offset + read_ptr, log_buffer, - avail - write_ptr); -/* read from slot start to write pointer */ -if (write_ptr) + tail); +/* read the rest from slot start */ +if (avail > tail)sof_mailbox_read (sdev, log_buffer_offset, - (u8 *)(log_buffer) + avail - write_ptr, - write_ptr); + (u8 *)(log_buffer) + tail, + avail - tail); }/* first write the number of bytes we have gathered */