device_virtio_snd/common_backend/
validation.rs

1// Copyright 2026 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Pure validation of guest-provided control requests. Everything in this module is free of I/O so
6//! that it can be exhaustively checked with Kani.
7
8use std::ops::Range;
9
10use thiserror::Error as ThisError;
11
12use crate::common::*;
13use crate::common_backend::stream_info::SetParams;
14use crate::constants::*;
15use crate::layout::*;
16
17/// Error returned when `VIRTIO_SND_R_PCM_SET_PARAMS` contains invalid or unsupported parameters.
18#[derive(ThisError, Debug, PartialEq, Eq)]
19pub(crate) enum SetParamsError {
20    #[error("Number of channels ({channels}) must be between {min} and {max}")]
21    InvalidChannels { channels: u8, min: u8, max: u8 },
22    #[error("PCM format {format} is not supported")]
23    UnsupportedFormat { format: u8 },
24    #[error("PCM frame rate {rate} is not supported")]
25    UnsupportedRate { rate: u8 },
26    #[error("No feature is supported (requested features: {features:#x})")]
27    UnsupportedFeatures { features: u32 },
28    #[error("period_bytes must not be zero")]
29    ZeroPeriodBytes,
30    #[error("buffer_bytes must not be zero")]
31    ZeroBufferBytes,
32    #[error("buffer_bytes ({buffer_bytes}) must be at least period_bytes ({period_bytes})")]
33    BufferSmallerThanPeriod {
34        buffer_bytes: usize,
35        period_bytes: usize,
36    },
37    #[error("buffer_bytes ({buffer_bytes}) must be divisible by period_bytes ({period_bytes})")]
38    BufferNotPeriodMultiple {
39        buffer_bytes: usize,
40        period_bytes: usize,
41    },
42}
43
44impl SetParamsError {
45    /// Maps the error to the corresponding Virtio Sound specification status code.
46    pub fn status_code(&self) -> u32 {
47        match self {
48            Self::InvalidChannels { .. }
49            | Self::UnsupportedFormat { .. }
50            | Self::UnsupportedRate { .. }
51            | Self::UnsupportedFeatures { .. } => VIRTIO_SND_S_NOT_SUPP,
52            Self::ZeroPeriodBytes
53            | Self::ZeroBufferBytes
54            | Self::BufferSmallerThanPeriod { .. }
55            | Self::BufferNotPeriodMultiple { .. } => VIRTIO_SND_S_BAD_MSG,
56        }
57    }
58}
59
60/// Validates a `virtio_snd_query_info` request against the number of available items.
61///
62/// Returns the index range of items to read, or `VIRTIO_SND_S_BAD_MSG` if `start_id + count`
63/// exceeds `len` or overflows `usize`.
64pub(crate) fn validate_query_info(
65    query_info: &virtio_snd_query_info,
66    len: usize,
67) -> Result<Range<usize>, u32> {
68    let start_id: usize = u32::from(query_info.start_id) as usize;
69    let count: usize = u32::from(query_info.count) as usize;
70    let end = match start_id.checked_add(count) {
71        Some(end) if end <= len => end,
72        _ => return Err(VIRTIO_SND_S_BAD_MSG),
73    };
74    Ok(start_id..end)
75}
76
77/// Validates parameters in `VIRTIO_SND_R_PCM_SET_PARAMS` against the stream's `pcm_info`.
78///
79/// Returns a validated [`SetParams`] struct, or a [`SetParamsError`] detailing the validation
80/// failure.
81pub(crate) fn validate_set_params(
82    set_params: &virtio_snd_pcm_set_params,
83    pcm_info: &virtio_snd_pcm_info,
84) -> Result<SetParams, SetParamsError> {
85    if set_params.channels < pcm_info.channels_min || set_params.channels > pcm_info.channels_max {
86        return Err(SetParamsError::InvalidChannels {
87            channels: set_params.channels,
88            min: pcm_info.channels_min,
89            max: pcm_info.channels_max,
90        });
91    }
92
93    // A u8 shift operand of 64 or greater overflows a 64-bit mask.
94    if set_params.format >= 64 || (u64::from(pcm_info.formats) & (1u64 << set_params.format)) == 0 {
95        return Err(SetParamsError::UnsupportedFormat {
96            format: set_params.format,
97        });
98    }
99
100    if set_params.rate >= 64 || (u64::from(pcm_info.rates) & (1u64 << set_params.rate)) == 0 {
101        return Err(SetParamsError::UnsupportedRate {
102            rate: set_params.rate,
103        });
104    }
105
106    if set_params.features != 0 {
107        return Err(SetParamsError::UnsupportedFeatures {
108            features: set_params.features.into(),
109        });
110    }
111
112    let period_bytes: usize = (u32::from(set_params.period_bytes)) as usize;
113    if period_bytes == 0 {
114        return Err(SetParamsError::ZeroPeriodBytes);
115    }
116
117    let buffer_bytes: usize = (u32::from(set_params.buffer_bytes)) as usize;
118    if buffer_bytes == 0 {
119        return Err(SetParamsError::ZeroBufferBytes);
120    }
121    if buffer_bytes < period_bytes {
122        return Err(SetParamsError::BufferSmallerThanPeriod {
123            buffer_bytes,
124            period_bytes,
125        });
126    }
127    if buffer_bytes % period_bytes != 0 {
128        return Err(SetParamsError::BufferNotPeriodMultiple {
129            buffer_bytes,
130            period_bytes,
131        });
132    }
133
134    // format and rate are guaranteed by the bitwise checks above to be supported by the device,
135    // which in crosvm is a subset of valid virtio sample formats and frame rates.
136    let format = from_virtio_sample_format(set_params.format).map_err(|_| {
137        SetParamsError::UnsupportedFormat {
138            format: set_params.format,
139        }
140    })?;
141    let frame_rate =
142        from_virtio_frame_rate(set_params.rate).map_err(|_| SetParamsError::UnsupportedRate {
143            rate: set_params.rate,
144        })?;
145
146    Ok(SetParams {
147        channels: set_params.channels,
148        format,
149        frame_rate,
150        buffer_bytes,
151        period_bytes,
152        dir: pcm_info.direction,
153    })
154}
155
156#[cfg(test)]
157pub(crate) mod tests {
158    use super::*;
159
160    fn dummy_pcm_info() -> virtio_snd_pcm_info {
161        virtio_snd_pcm_info {
162            channels_min: 1,
163            channels_max: 2,
164            formats: ((1 << VIRTIO_SND_PCM_FMT_S16) | (1 << VIRTIO_SND_PCM_FMT_U8)).into(),
165            rates: ((1 << VIRTIO_SND_PCM_RATE_44100) | (1 << VIRTIO_SND_PCM_RATE_48000)).into(),
166            direction: VIRTIO_SND_D_OUTPUT,
167            ..Default::default()
168        }
169    }
170
171    #[test]
172    fn test_validate_query_info_success() {
173        let q = virtio_snd_query_info {
174            hdr: virtio_snd_hdr {
175                code: VIRTIO_SND_R_JACK_INFO.into(),
176            },
177            start_id: 1.into(),
178            count: 3.into(),
179            size: 0.into(),
180        };
181        assert_eq!(validate_query_info(&q, 10), Ok(1..4));
182    }
183
184    #[test]
185    fn test_validate_query_info_out_of_bounds() {
186        let q = virtio_snd_query_info {
187            hdr: virtio_snd_hdr {
188                code: VIRTIO_SND_R_JACK_INFO.into(),
189            },
190            start_id: 8.into(),
191            count: 3.into(),
192            size: 0.into(),
193        };
194        assert_eq!(validate_query_info(&q, 10), Err(VIRTIO_SND_S_BAD_MSG));
195    }
196
197    #[test]
198    fn test_validate_query_info_overflow() {
199        let q = virtio_snd_query_info {
200            hdr: virtio_snd_hdr {
201                code: VIRTIO_SND_R_JACK_INFO.into(),
202            },
203            start_id: u32::MAX.into(),
204            count: 1.into(),
205            size: 0.into(),
206        };
207        assert_eq!(validate_query_info(&q, 10), Err(VIRTIO_SND_S_BAD_MSG));
208    }
209
210    #[test]
211    fn test_validate_set_params_success() {
212        let pcm_info = dummy_pcm_info();
213        let set_params = virtio_snd_pcm_set_params {
214            channels: 2,
215            format: VIRTIO_SND_PCM_FMT_S16,
216            rate: VIRTIO_SND_PCM_RATE_48000,
217            buffer_bytes: 4096.into(),
218            period_bytes: 1024.into(),
219            features: 0.into(),
220            ..Default::default()
221        };
222        let res = validate_set_params(&set_params, &pcm_info);
223        assert!(res.is_ok());
224        let params = res.unwrap();
225        assert_eq!(params.channels, 2);
226        assert_eq!(params.buffer_bytes, 4096);
227        assert_eq!(params.period_bytes, 1024);
228        assert_eq!(params.dir, VIRTIO_SND_D_OUTPUT);
229    }
230
231    #[test]
232    fn test_validate_set_params_zero_period() {
233        let pcm_info = dummy_pcm_info();
234        let set_params = virtio_snd_pcm_set_params {
235            channels: 2,
236            format: VIRTIO_SND_PCM_FMT_S16,
237            rate: VIRTIO_SND_PCM_RATE_44100,
238            buffer_bytes: 4096.into(),
239            period_bytes: 0.into(),
240            features: 0.into(),
241            ..Default::default()
242        };
243        assert_eq!(
244            validate_set_params(&set_params, &pcm_info),
245            Err(SetParamsError::ZeroPeriodBytes)
246        );
247    }
248
249    #[test]
250    fn test_validate_set_params_buffer_smaller_than_period() {
251        let pcm_info = dummy_pcm_info();
252        let set_params = virtio_snd_pcm_set_params {
253            channels: 2,
254            format: VIRTIO_SND_PCM_FMT_S16,
255            rate: VIRTIO_SND_PCM_RATE_44100,
256            buffer_bytes: 512.into(),
257            period_bytes: 1024.into(),
258            features: 0.into(),
259            ..Default::default()
260        };
261        assert_eq!(
262            validate_set_params(&set_params, &pcm_info),
263            Err(SetParamsError::BufferSmallerThanPeriod {
264                buffer_bytes: 512,
265                period_bytes: 1024,
266            })
267        );
268    }
269
270    #[test]
271    fn test_validate_set_params_format_overflow() {
272        let pcm_info = dummy_pcm_info();
273        let set_params = virtio_snd_pcm_set_params {
274            channels: 2,
275            format: 100,
276            rate: VIRTIO_SND_PCM_RATE_44100,
277            buffer_bytes: 4096.into(),
278            period_bytes: 1024.into(),
279            features: 0.into(),
280            ..Default::default()
281        };
282        assert_eq!(
283            validate_set_params(&set_params, &pcm_info),
284            Err(SetParamsError::UnsupportedFormat { format: 100 })
285        );
286    }
287
288    #[test]
289    fn test_validate_set_params_rate_overflow() {
290        let pcm_info = dummy_pcm_info();
291        let set_params = virtio_snd_pcm_set_params {
292            channels: 2,
293            format: VIRTIO_SND_PCM_FMT_S16,
294            rate: 200,
295            buffer_bytes: 4096.into(),
296            period_bytes: 1024.into(),
297            features: 0.into(),
298            ..Default::default()
299        };
300        assert_eq!(
301            validate_set_params(&set_params, &pcm_info),
302            Err(SetParamsError::UnsupportedRate { rate: 200 })
303        );
304    }
305}
306
307#[cfg(kani)]
308mod kani_proofs {
309    use super::*;
310
311    #[kani::proof]
312    fn proof_validate_query_info() {
313        let start_id: u32 = kani::any();
314        let count: u32 = kani::any();
315        let len: usize = kani::any();
316
317        let query = virtio_snd_query_info {
318            hdr: virtio_snd_hdr { code: 0.into() },
319            start_id: start_id.into(),
320            count: count.into(),
321            size: 0.into(),
322        };
323
324        if let Ok(range) = validate_query_info(&query, len) {
325            assert!(range.start <= range.end);
326            assert!(range.end <= len);
327            assert_eq!(range.end - range.start, count as usize);
328        }
329    }
330
331    #[kani::proof]
332    fn proof_validate_set_params() {
333        let channels: u8 = kani::any();
334        let format: u8 = kani::any();
335        let rate: u8 = kani::any();
336        let buffer_bytes: u32 = kani::any();
337        let period_bytes: u32 = kani::any();
338        let features: u32 = kani::any();
339
340        let set_params = virtio_snd_pcm_set_params {
341            hdr: virtio_snd_pcm_hdr {
342                hdr: virtio_snd_hdr { code: 0.into() },
343                stream_id: 0.into(),
344            },
345            buffer_bytes: buffer_bytes.into(),
346            period_bytes: period_bytes.into(),
347            features: features.into(),
348            channels,
349            format,
350            rate,
351            padding: 0,
352        };
353
354        let pcm_info = virtio_snd_pcm_info {
355            hdr: virtio_snd_info {
356                hda_fn_nid: 0.into(),
357            },
358            features: 0.into(),
359            formats: crate::common_backend::SUPPORTED_FORMATS.into(),
360            rates: crate::common_backend::SUPPORTED_FRAME_RATES.into(),
361            direction: VIRTIO_SND_D_OUTPUT,
362            channels_min: 1,
363            channels_max: 2,
364            padding: [0; 5],
365        };
366
367        if let Ok(p) = validate_set_params(&set_params, &pcm_info) {
368            assert!(p.channels >= 1 && p.channels <= 2);
369            assert!(p.period_bytes > 0);
370            assert!(p.buffer_bytes >= p.period_bytes);
371            assert_eq!(p.dir, VIRTIO_SND_D_OUTPUT);
372        }
373    }
374
375    #[kani::proof]
376    fn proof_hardcoded_capabilities_are_convertible() {
377        let bit: u8 = kani::any();
378        kani::assume(bit < 64);
379        if (crate::common_backend::SUPPORTED_FORMATS & (1u64 << bit)) != 0 {
380            assert!(from_virtio_sample_format(bit).is_ok());
381        }
382        if (crate::common_backend::SUPPORTED_FRAME_RATES & (1u64 << bit)) != 0 {
383            assert!(from_virtio_frame_rate(bit).is_ok());
384        }
385    }
386
387    #[kani::proof]
388    fn proof_format_and_rate_roundtrip() {
389        let fmt_idx: u8 = kani::any();
390        kani::assume(fmt_idx < 64);
391        if let Ok(sample_fmt) = from_virtio_sample_format(fmt_idx) {
392            let back = from_sample_format(sample_fmt);
393            assert_eq!(back, fmt_idx);
394        }
395
396        let rate_idx: u8 = kani::any();
397        kani::assume(rate_idx < 64);
398        if let Ok(frame_rate) = from_virtio_frame_rate(rate_idx) {
399            let back = virtio_frame_rate(frame_rate);
400            assert_eq!(back.unwrap(), rate_idx);
401        }
402    }
403}