Skip to main content

zfs_core/
nvlist.rs

1//! XDR-encoded nvlist (name/value pair list) parser — the ZFS pool config.
2//!
3//! Each vdev label carries a 112 KiB packed nvlist describing the pool: its
4//! `version`, `name`, `pool_guid`, `txg`, and a nested `vdev_tree` giving
5//! `ashift`/`asize` and the vdev topology. This is the pool bootstrap.
6//!
7//! # On-disk layout (verified against `zdb -l`)
8//!
9//! The packed buffer opens with a 4-byte header — `encoding` (`0x01` = XDR),
10//! `endian` (host order of the writer), and two reserved bytes — followed by the
11//! XDR nvlist body. Every integer in the body is **big-endian** (XDR), regardless
12//! of the pool's native order. The body is:
13//!
14//! - `nvl_version` (`i32`), `nvl_nvflag` (`u32`), then a sequence of nvpairs.
15//! - Each nvpair: `encoded_size` (`i32`), `decoded_size` (`i32`), name as an XDR
16//!   string (`len` `i32` + bytes padded up to a 4-byte boundary), `data_type`
17//!   (`i32`), `nelem` (`i32`), then the value(s).
18//! - A terminating nvpair with `encoded_size == 0` ends the list.
19//! - A nested nvlist value (`DATA_TYPE_NVLIST`) is `nvl_version` + `nvl_nvflag`
20//!   followed by its own nvpairs (no repeated 4-byte packed header).
21
22use crate::bytes::{be_u32, be_u64, u8_at};
23use crate::error::ZfsError;
24
25/// XDR encoding marker for a packed nvlist (`NV_ENCODE_XDR`).
26const NV_ENCODE_XDR: u8 = 1;
27
28/// `DATA_TYPE_UINT64`.
29const DATA_TYPE_UINT64: i32 = 8;
30/// `DATA_TYPE_STRING`.
31const DATA_TYPE_STRING: i32 = 9;
32/// `DATA_TYPE_BYTE_ARRAY` — an opaque byte run, `nelem` bytes long.
33///
34/// This is how ZFS stores an extended attribute's VALUE in the `ZPL_DXATTR`
35/// nvlist, so it is not an optional nicety for that path.
36const DATA_TYPE_BYTE_ARRAY: i32 = 10;
37/// `DATA_TYPE_NVLIST` (a nested nvlist).
38const DATA_TYPE_NVLIST: i32 = 19;
39/// `DATA_TYPE_UINT8_ARRAY` — the same payload shape as a byte array.
40const DATA_TYPE_UINT8_ARRAY: i32 = 26;
41
42/// Upper bound on an nvpair name length (bytes) — allocation-bomb guard.
43const MAX_NAME_LEN: u64 = 4096;
44/// Upper bound on a string value length (bytes) — allocation-bomb guard.
45const MAX_STRING_LEN: u64 = 65536;
46/// Upper bound on the number of nvpairs in one list — allocation-bomb guard.
47const MAX_PAIRS: usize = 4096;
48/// Upper bound on nested-nvlist recursion depth — allocation-bomb guard.
49const MAX_DEPTH: usize = 16;
50
51/// A decoded nvpair value (the subset P0 needs from the pool config).
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum NvValue {
54    /// `DATA_TYPE_UINT64`.
55    U64(u64),
56    /// `DATA_TYPE_STRING`.
57    Str(String),
58    /// `DATA_TYPE_NVLIST` (nested).
59    NvList(NvList),
60    /// `DATA_TYPE_BYTE_ARRAY` / `DATA_TYPE_UINT8_ARRAY` — opaque bytes.
61    Bytes(Vec<u8>),
62}
63
64/// A decoded nvlist: an ordered set of `(name, value)` pairs.
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct NvList {
67    pairs: Vec<(String, NvValue)>,
68}
69
70impl NvList {
71    /// Look up a name, returning the first matching value.
72    #[must_use]
73    pub fn get(&self, name: &str) -> Option<&NvValue> {
74        self.pairs.iter().find(|(n, _)| n == name).map(|(_, v)| v)
75    }
76
77    /// Convenience: look up a `u64`-typed value by name.
78    #[must_use]
79    pub fn get_u64(&self, name: &str) -> Option<u64> {
80        match self.get(name) {
81            Some(NvValue::U64(v)) => Some(*v),
82            _ => None,
83        }
84    }
85
86    /// Convenience: look up a string-typed value by name.
87    #[must_use]
88    pub fn get_str(&self, name: &str) -> Option<&str> {
89        match self.get(name) {
90            Some(NvValue::Str(s)) => Some(s.as_str()),
91            _ => None,
92        }
93    }
94
95    /// The byte-array value stored under `name`, if the pair is one.
96    #[must_use]
97    pub fn get_bytes(&self, name: &str) -> Option<&[u8]> {
98        match self.get(name)? {
99            NvValue::Bytes(b) => Some(b),
100            _ => None,
101        }
102    }
103
104    /// Convenience: look up a nested-nvlist value by name.
105    #[must_use]
106    pub fn get_nvlist(&self, name: &str) -> Option<&NvList> {
107        match self.get(name) {
108            Some(NvValue::NvList(l)) => Some(l),
109            _ => None,
110        }
111    }
112
113    /// All `(name, value)` pairs in on-disk order.
114    #[must_use]
115    pub fn pairs(&self) -> &[(String, NvValue)] {
116        &self.pairs
117    }
118
119    /// The nested `vdev_tree` decoded into its P0 fields, if present.
120    #[must_use]
121    pub fn vdev_tree(&self) -> Option<VdevTree> {
122        self.get_nvlist("vdev_tree").map(VdevTree::from_nvlist)
123    }
124}
125
126/// The P0 subset of the nested `vdev_tree` config.
127#[derive(Debug, Clone, PartialEq, Eq, Default)]
128pub struct VdevTree {
129    /// vdev `type` (e.g. `"file"`, `"disk"`, `"raidz"`, `"mirror"`).
130    pub vdev_type: String,
131    /// `ashift` — log2 of the minimum allocation/sector size.
132    pub ashift: u64,
133    /// `asize` — allocatable size of the vdev in bytes.
134    pub asize: u64,
135    /// vdev `guid`.
136    pub guid: u64,
137}
138
139impl VdevTree {
140    /// Extract the P0 fields from an already-decoded `vdev_tree` nvlist.
141    #[must_use]
142    pub fn from_nvlist(nv: &NvList) -> Self {
143        Self {
144            vdev_type: nv.get_str("type").unwrap_or_default().to_owned(),
145            ashift: nv.get_u64("ashift").unwrap_or(0),
146            asize: nv.get_u64("asize").unwrap_or(0),
147            guid: nv.get_u64("guid").unwrap_or(0),
148        }
149    }
150}
151
152/// Parse a packed nvlist config from `data` (the 112 KiB label nvlist region, or
153/// any buffer that begins with the 4-byte packed header).
154///
155/// # Errors
156///
157/// - [`ZfsError::BadNvlistEncoding`] if the encoding byte is not XDR.
158/// - [`ZfsError::NvlistBomb`] if a length/count field exceeds its sane cap.
159/// - [`ZfsError::Truncated`] if the buffer ends mid-structure.
160pub fn parse(data: &[u8]) -> Result<NvList, ZfsError> {
161    let encoding = u8_at(data, 0);
162    if encoding != NV_ENCODE_XDR {
163        return Err(ZfsError::BadNvlistEncoding {
164            encoding,
165            offset: 0,
166        });
167    }
168    if data.len() < 4 {
169        return Err(ZfsError::Truncated {
170            structure: "nvlist header",
171            need: 4,
172            have: data.len(),
173        });
174    }
175    // The XDR body follows the 4-byte packed header (encoding, endian, 2 rsvd).
176    let (list, _consumed) = parse_body(data, 4, 0)?;
177    Ok(list)
178}
179
180/// Parse an nvlist body (version + nvflag + nvpairs) starting at `off`.
181///
182/// Returns the decoded list and the offset just past its terminator. `depth`
183/// bounds nested recursion.
184fn parse_body(data: &[u8], off: usize, depth: usize) -> Result<(NvList, usize), ZfsError> {
185    if depth > MAX_DEPTH {
186        return Err(ZfsError::NvlistBomb {
187            field: "depth",
188            value: depth as u64,
189            cap: MAX_DEPTH as u64,
190        });
191    }
192    // nvl_version (i32) + nvl_nvflag (u32).
193    let mut cur = off.checked_add(8).ok_or(ZfsError::Truncated {
194        structure: "nvlist body header",
195        need: 8,
196        have: data.len().saturating_sub(off),
197    })?;
198    let mut list = NvList::default();
199
200    for _ in 0..MAX_PAIRS {
201        let encoded_size = be_u32(data, cur) as i32;
202        if encoded_size == 0 {
203            // Terminator nvpair (encoded_size == 0, decoded_size == 0).
204            cur = cur.saturating_add(8);
205            return Ok((list, cur));
206        }
207        if encoded_size < 0 {
208            return Err(ZfsError::NvlistBomb {
209                field: "encoded_size",
210                value: u64::from(encoded_size.unsigned_abs()),
211                cap: u64::from(i32::MAX.unsigned_abs()),
212            });
213        }
214        let pair_start = cur;
215        // encoded_size (4) + decoded_size (4) then the name string.
216        let name_off = cur.saturating_add(8);
217        let (name, after_name) = read_xdr_string(data, name_off, "nvpair name", MAX_NAME_LEN)?;
218        // data_type (i32) + nelem (i32).
219        let data_type = be_u32(data, after_name) as i32;
220        let value_off = after_name.saturating_add(8);
221
222        let value = match data_type {
223            DATA_TYPE_UINT64 => NvValue::U64(be_u64(data, value_off)),
224            DATA_TYPE_STRING => {
225                let (s, _) = read_xdr_string(data, value_off, "nvpair string", MAX_STRING_LEN)?;
226                NvValue::Str(s)
227            }
228            DATA_TYPE_NVLIST => {
229                let (nested, _) = parse_body(data, value_off, depth + 1)?;
230                NvValue::NvList(nested)
231            }
232            DATA_TYPE_BYTE_ARRAY | DATA_TYPE_UINT8_ARRAY => {
233                // ZFS encodes a byte array with xdr_opaque: the bytes are
234                // CONTIGUOUS, padded to the next 4-byte boundary. (An earlier
235                // attempt assumed XDR's one-4-byte-word-per-element rule, which
236                // returns the right LENGTH built from every fourth byte -- a
237                // plausible-looking wrong value. Settled by dumping the packed
238                // DXATTR of the reference pool:
239                //   00 00 00 0a  00 00 00 0a  74 69 6e 79 2d 76 61 6c 75 65
240                //   type=10      nelem=10     "tiny-value"                  )
241                let n = be_u32(data, after_name.saturating_add(4)) as usize;
242                if n as u64 > MAX_STRING_LEN {
243                    return Err(ZfsError::NvlistBomb {
244                        field: "byte_array nelem",
245                        value: n as u64,
246                        cap: MAX_STRING_LEN,
247                    });
248                }
249                let end = value_off.saturating_add(n);
250                let bytes = data.get(value_off..end).unwrap_or(&[]);
251                NvValue::Bytes(bytes.to_vec())
252            }
253            // Types P0 does not consume (arrays, bool, nvlist arrays, …) are
254            // skipped by encoded_size rather than failing — the config carries
255            // fields we do not need, and skipping keeps the walk robust.
256            _ => {
257                cur = pair_start.saturating_add(encoded_size as usize);
258                continue;
259            }
260        };
261        list.pairs.push((name, value));
262        cur = pair_start.saturating_add(encoded_size as usize);
263        if cur >= data.len() {
264            // Ran off the end without a terminator — surface what we decoded.
265            return Ok((list, cur));
266        }
267    }
268    Err(ZfsError::NvlistBomb {
269        field: "pair_count",
270        value: MAX_PAIRS as u64,
271        cap: MAX_PAIRS as u64,
272    })
273}
274
275/// Read an XDR string at `off`: a big-endian `i32` length followed by that many
276/// bytes, padded up to a 4-byte boundary. Returns the string and the offset just
277/// past the padded value.
278fn read_xdr_string(
279    data: &[u8],
280    off: usize,
281    field: &'static str,
282    cap: u64,
283) -> Result<(String, usize), ZfsError> {
284    let len = be_u32(data, off) as i32;
285    if len < 0 {
286        return Err(ZfsError::NvlistBomb {
287            field,
288            value: u64::from(len.unsigned_abs()),
289            cap,
290        });
291    }
292    let len = u64::from(len.unsigned_abs());
293    if len > cap {
294        return Err(ZfsError::NvlistBomb {
295            field,
296            value: len,
297            cap,
298        });
299    }
300    let len = len as usize;
301    let start = off.saturating_add(4);
302    let end = start.checked_add(len).ok_or(ZfsError::Truncated {
303        structure: "xdr string",
304        need: len,
305        have: data.len().saturating_sub(start),
306    })?;
307    let raw = data.get(start..end).ok_or(ZfsError::Truncated {
308        structure: "xdr string",
309        need: len,
310        have: data.len().saturating_sub(start),
311    })?;
312    // XDR pads to a 4-byte boundary.
313    let padded = (len + 3) & !3;
314    let next = start.saturating_add(padded);
315    Ok((String::from_utf8_lossy(raw).into_owned(), next))
316}
317
318#[cfg(test)]
319mod unit {
320    use super::{parse, NvList, NvValue, VdevTree, DATA_TYPE_BYTE_ARRAY, MAX_STRING_LEN};
321    use crate::error::ZfsError;
322
323    /// A minimal packed XDR nvlist: header + version/nvflag + one uint64 pair
324    /// named `n` + terminator. Encodes big-endian throughout.
325    fn one_u64(name: &str, val: u64) -> Vec<u8> {
326        let mut b = vec![0x01, 0x01, 0x00, 0x00]; // XDR header
327        b.extend_from_slice(&0i32.to_be_bytes()); // nvl_version
328        b.extend_from_slice(&1u32.to_be_bytes()); // nvl_nvflag
329                                                  // nvpair: encoded_size, decoded_size, name (xdr string), type, nelem, value
330        let name_bytes = name.as_bytes();
331        let padded = (name_bytes.len() + 3) & !3;
332        let mut pair = Vec::new();
333        pair.extend_from_slice(&(name_bytes.len() as i32).to_be_bytes());
334        pair.extend_from_slice(name_bytes);
335        pair.resize(4 + padded, 0);
336        pair.extend_from_slice(&8i32.to_be_bytes()); // DATA_TYPE_UINT64
337        pair.extend_from_slice(&1i32.to_be_bytes()); // nelem
338        pair.extend_from_slice(&val.to_be_bytes());
339        let encoded = 8 + pair.len();
340        b.extend_from_slice(&(encoded as i32).to_be_bytes());
341        b.extend_from_slice(&(encoded as i32).to_be_bytes());
342        b.extend_from_slice(&pair);
343        b.extend_from_slice(&0i32.to_be_bytes()); // terminator encoded_size
344        b.extend_from_slice(&0i32.to_be_bytes()); // terminator decoded_size
345        b
346    }
347
348    #[test]
349    fn parses_a_single_u64_pair() {
350        let buf = one_u64("answer", 42);
351        let nv = parse(&buf).unwrap();
352        assert_eq!(nv.get_u64("answer"), Some(42));
353        assert_eq!(nv.pairs().len(), 1);
354    }
355
356    #[test]
357    fn bad_encoding_is_rejected_with_the_byte() {
358        let buf = [0x02, 0x01, 0x00, 0x00, 0, 0, 0, 0];
359        assert_eq!(
360            parse(&buf),
361            Err(ZfsError::BadNvlistEncoding {
362                encoding: 0x02,
363                offset: 0
364            })
365        );
366    }
367
368    #[test]
369    fn header_shorter_than_four_bytes_is_truncated() {
370        let buf = [0x01, 0x01]; // right encoding byte, too short
371        assert!(matches!(parse(&buf), Err(ZfsError::Truncated { .. })));
372    }
373
374    #[test]
375    fn empty_buffer_reports_zero_encoding() {
376        // u8_at yields 0 out of range, so an empty buffer reads encoding 0.
377        assert!(matches!(
378            parse(&[]),
379            Err(ZfsError::BadNvlistEncoding { encoding: 0, .. })
380        ));
381    }
382
383    #[test]
384    fn oversized_name_length_is_capped() {
385        let mut b = vec![0x01, 0x01, 0x00, 0x00];
386        b.extend_from_slice(&0i32.to_be_bytes());
387        b.extend_from_slice(&1u32.to_be_bytes());
388        b.extend_from_slice(&64i32.to_be_bytes()); // encoded_size
389        b.extend_from_slice(&64i32.to_be_bytes()); // decoded_size
390        b.extend_from_slice(&1_000_000i32.to_be_bytes()); // name len — bomb
391        b.resize(256, 0);
392        assert!(matches!(
393            parse(&b),
394            Err(ZfsError::NvlistBomb {
395                field: "nvpair name",
396                ..
397            })
398        ));
399    }
400
401    #[test]
402    fn negative_name_length_is_rejected() {
403        let mut b = vec![0x01, 0x01, 0x00, 0x00];
404        b.extend_from_slice(&0i32.to_be_bytes());
405        b.extend_from_slice(&1u32.to_be_bytes());
406        b.extend_from_slice(&64i32.to_be_bytes());
407        b.extend_from_slice(&64i32.to_be_bytes());
408        b.extend_from_slice(&(-1i32).to_be_bytes()); // negative len
409        b.resize(256, 0);
410        assert!(matches!(parse(&b), Err(ZfsError::NvlistBomb { .. })));
411    }
412
413    #[test]
414    fn negative_encoded_size_is_rejected() {
415        let mut b = vec![0x01, 0x01, 0x00, 0x00];
416        b.extend_from_slice(&0i32.to_be_bytes());
417        b.extend_from_slice(&1u32.to_be_bytes());
418        b.extend_from_slice(&(-1i32).to_be_bytes()); // negative encoded_size
419        b.resize(64, 0);
420        assert!(matches!(
421            parse(&b),
422            Err(ZfsError::NvlistBomb {
423                field: "encoded_size",
424                ..
425            })
426        ));
427    }
428
429    #[test]
430    fn unknown_type_is_skipped_by_encoded_size() {
431        // A pair of an unhandled type (e.g. DATA_TYPE_BOOLEAN=1) is skipped; a
432        // following uint64 pair still decodes.
433        let mut b = vec![0x01, 0x01, 0x00, 0x00];
434        b.extend_from_slice(&0i32.to_be_bytes());
435        b.extend_from_slice(&1u32.to_be_bytes());
436        // unknown-type pair: name "x", type 1, nelem 0
437        let mut p = Vec::new();
438        p.extend_from_slice(&1i32.to_be_bytes()); // name len
439        p.extend_from_slice(b"x\0\0\0"); // padded
440        p.extend_from_slice(&1i32.to_be_bytes()); // DATA_TYPE_BOOLEAN
441        p.extend_from_slice(&0i32.to_be_bytes()); // nelem
442        let enc = 8 + p.len();
443        b.extend_from_slice(&(enc as i32).to_be_bytes());
444        b.extend_from_slice(&(enc as i32).to_be_bytes());
445        b.extend_from_slice(&p);
446        // then a normal uint64 pair
447        let tail = one_u64("k", 7);
448        b.extend_from_slice(&tail[12..]); // skip its header+version+nvflag
449        let nv = parse(&b).unwrap();
450        assert_eq!(nv.get_u64("k"), Some(7));
451        assert!(nv.get("x").is_none());
452    }
453
454    #[test]
455    fn typed_getters_return_none_on_mismatch() {
456        let nv = parse(&one_u64("n", 3)).unwrap();
457        assert!(nv.get_str("n").is_none()); // it is a u64, not a string
458        assert!(nv.get_nvlist("n").is_none());
459        assert!(nv.get_u64("absent").is_none());
460        assert!(nv.get_str("absent").is_none());
461        assert!(nv.get_nvlist("absent").is_none());
462        assert!(nv.vdev_tree().is_none());
463    }
464
465    #[test]
466    fn vdev_tree_defaults_when_fields_absent() {
467        let vt = VdevTree::from_nvlist(&NvList::default());
468        assert_eq!(vt, VdevTree::default());
469        assert_eq!(vt.vdev_type, "");
470    }
471
472    #[test]
473    fn nvvalue_equality() {
474        assert_eq!(NvValue::U64(1), NvValue::U64(1));
475        assert_ne!(NvValue::U64(1), NvValue::Str("1".into()));
476    }
477
478    /// Serialize one nvpair (name, big-endian type, value bytes) into `out`.
479    fn pair(out: &mut Vec<u8>, name: &[u8], data_type: i32, value: &[u8]) {
480        let padded = (name.len() + 3) & !3;
481        let mut p = Vec::new();
482        p.extend_from_slice(&(name.len() as i32).to_be_bytes());
483        p.extend_from_slice(name);
484        p.resize(4 + padded, 0);
485        p.extend_from_slice(&data_type.to_be_bytes());
486        p.extend_from_slice(&1i32.to_be_bytes()); // nelem
487        p.extend_from_slice(value);
488        let enc = 8 + p.len();
489        out.extend_from_slice(&(enc as i32).to_be_bytes()); // encoded_size
490        out.extend_from_slice(&(enc as i32).to_be_bytes()); // decoded_size
491        out.extend_from_slice(&p);
492    }
493
494    #[test]
495    fn excessive_nesting_depth_is_capped() {
496        // Build a chain of nested NVLIST pairs deeper than MAX_DEPTH (16). Each
497        // nested value is a body (version + nvflag + child + terminator).
498        fn nested_value(remaining: usize) -> Vec<u8> {
499            let mut body = Vec::new();
500            body.extend_from_slice(&0i32.to_be_bytes()); // nvl_version
501            body.extend_from_slice(&1u32.to_be_bytes()); // nvl_nvflag
502            if remaining > 0 {
503                let child = nested_value(remaining - 1);
504                pair(&mut body, b"n", 19, &child); // DATA_TYPE_NVLIST
505            }
506            body.extend_from_slice(&0i32.to_be_bytes()); // terminator
507            body.extend_from_slice(&0i32.to_be_bytes());
508            body
509        }
510        let mut buf = vec![0x01, 0x01, 0x00, 0x00]; // XDR header
511        buf.extend_from_slice(&nested_value(20)); // 20 > MAX_DEPTH
512        assert!(matches!(
513            parse(&buf),
514            Err(ZfsError::NvlistBomb { field: "depth", .. })
515        ));
516    }
517
518    #[test]
519    fn pair_flush_with_the_buffer_at_the_end_returns_what_decoded() {
520        // One valid uint64 pair, then the buffer ends exactly at the pair
521        // boundary (no terminator) — the decoder returns the pair it recovered
522        // rather than looping or reading past the end.
523        let mut buf = vec![0x01, 0x01, 0x00, 0x00];
524        buf.extend_from_slice(&0i32.to_be_bytes()); // nvl_version
525        buf.extend_from_slice(&1u32.to_be_bytes()); // nvl_nvflag
526        pair(&mut buf, b"only", 8, &99u64.to_be_bytes());
527        // No terminator appended: `cur` lands at `data.len()` after the pair.
528        let nv = parse(&buf).unwrap();
529        assert_eq!(nv.get_u64("only"), Some(99));
530    }
531
532    #[test]
533    fn too_many_pairs_is_capped() {
534        // MAX_PAIRS+1 tiny uint64 pairs with no terminator: the loop runs
535        // MAX_PAIRS times without hitting a terminator or the end, then the
536        // pair-count bomb fires.
537        let mut buf = vec![0x01, 0x01, 0x00, 0x00];
538        buf.extend_from_slice(&0i32.to_be_bytes()); // nvl_version
539        buf.extend_from_slice(&1u32.to_be_bytes()); // nvl_nvflag
540        for _ in 0..=super::MAX_PAIRS {
541            pair(&mut buf, b"k", 8, &0u64.to_be_bytes()); // DATA_TYPE_UINT64
542        }
543        // No terminator; buffer holds all pairs so `cur < data.len()` throughout.
544        assert!(matches!(
545            parse(&buf),
546            Err(ZfsError::NvlistBomb {
547                field: "pair_count",
548                ..
549            })
550        ));
551    }
552
553    /// A packed nvlist holding one byte-array pair, with `nelem` written as
554    /// given (so a test can lie about it) and `value` stored xdr_opaque-style.
555    fn one_bytes(name: &str, nelem: u32, value: &[u8]) -> Vec<u8> {
556        let mut b = vec![0x01, 0x01, 0x00, 0x00];
557        b.extend_from_slice(&0i32.to_be_bytes());
558        b.extend_from_slice(&1u32.to_be_bytes());
559        let name_bytes = name.as_bytes();
560        let padded = (name_bytes.len() + 3) & !3;
561        let mut pair = Vec::new();
562        pair.extend_from_slice(&(name_bytes.len() as i32).to_be_bytes());
563        pair.extend_from_slice(name_bytes);
564        pair.resize(4 + padded, 0);
565        pair.extend_from_slice(&DATA_TYPE_BYTE_ARRAY.to_be_bytes());
566        pair.extend_from_slice(&nelem.to_be_bytes());
567        pair.extend_from_slice(value);
568        pair.resize((pair.len() + 3) & !3, 0);
569        let encoded = 8 + pair.len();
570        b.extend_from_slice(&(encoded as i32).to_be_bytes());
571        b.extend_from_slice(&(encoded as i32).to_be_bytes());
572        b.extend_from_slice(&pair);
573        b.extend_from_slice(&0i32.to_be_bytes());
574        b.extend_from_slice(&0i32.to_be_bytes());
575        b
576    }
577
578    #[test]
579    fn get_bytes_returns_byte_arrays_only() {
580        let nv = parse(&one_bytes("small", 10, b"tiny-value")).unwrap();
581        assert_eq!(nv.get_bytes("small"), Some(&b"tiny-value"[..]));
582        assert_eq!(nv.get_bytes("absent"), None);
583        let other = parse(&one_u64("answer", 42)).unwrap();
584        assert_eq!(other.get_bytes("answer"), None, "a u64 is not a byte array");
585    }
586
587    #[test]
588    fn oversized_byte_array_count_is_capped() {
589        let lie = u32::try_from(MAX_STRING_LEN + 1).unwrap();
590        assert!(matches!(
591            parse(&one_bytes("big", lie, b"x")),
592            Err(ZfsError::NvlistBomb {
593                field: "byte_array nelem",
594                ..
595            })
596        ));
597    }
598}