From 7255036df65032fea258de400ac78ffc1a9ddb36 Mon Sep 17 00:00:00 2001 From: Manos Pitsidianakis Date: Tue, 31 Oct 2023 15:35:50 +0200 Subject: [PATCH] sound/pipewire: prevent unsigned sub overflow A subtraction between unsigned integers is made, which by default panics on overflow. However, we don't really need to know the difference, only that it is not zero or less. Signed-off-by: Manos Pitsidianakis --- .../src/audio_backends/pipewire.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/staging/vhost-device-sound/src/audio_backends/pipewire.rs b/staging/vhost-device-sound/src/audio_backends/pipewire.rs index a2fe72e..e9216ba 100644 --- a/staging/vhost-device-sound/src/audio_backends/pipewire.rs +++ b/staging/vhost-device-sound/src/audio_backends/pipewire.rs @@ -3,7 +3,7 @@ use std::{ collections::HashMap, - convert::TryInto, + convert::TryFrom, mem::size_of, ptr, sync::{Arc, RwLock}, @@ -362,8 +362,10 @@ impl AudioBackend for PwBackend { }; let mut buf_pos = buffer.pos; - let avail = (buffer.desc_len() as usize - buf_pos) as i32; - let n_bytes = n_samples.min(avail.try_into().unwrap()); + let avail = usize::try_from(buffer.desc_len()) + .unwrap() + .saturating_sub(buf_pos); + let n_bytes = n_samples.min(avail); let p = &slice[start..start + n_bytes]; if buffer @@ -400,13 +402,15 @@ impl AudioBackend for PwBackend { let mut start = buffer.pos; - let avail = (buffer.desc_len() - start as u32) as i32; + let avail = usize::try_from(buffer.desc_len()) + .unwrap() + .saturating_sub(start); - if avail < n_bytes as i32 { - n_bytes = avail.try_into().unwrap(); + if avail < n_bytes { + n_bytes = avail; } let p = &mut slice[0..n_bytes]; - if avail <= 0 { + if avail == 0 { // SAFETY: We have assured above that the pointer is not // null // safe to zero-initialize the pointer.