Skip to main content

ostrya_gvariant/
ser.rs

1use crate::codec::{TupleWriter, write_array};
2use crate::de::MAX_VALUE_DEPTH;
3use crate::{Error, GvEncode, Result, Type, Value};
4
5/// Serializes `value` as type `ty` in GVariant normal form.
6///
7/// The serializer writes framing offsets and multi-byte scalars in
8/// little-endian byte order. This is the normal-form byte order on the
9/// little-endian targets that ostree supports.
10///
11/// The on-disk format defines some fields as big-endian: uids, gids, modes,
12/// timestamps, and sizes. The caller converts the values of these fields
13/// before serialization.
14///
15/// # Errors
16///
17/// - [`Error::TypeMismatch`] if `value` does not match `ty`. This includes a
18///   tuple or a dict entry with a different number of members. It also
19///   includes a [`Value::Array`] of [`Value::Byte`] for the type `ay`, which
20///   needs [`Value::Bytes`].
21/// - [`Error::InvalidValue`] if a [`Value::Str`] holds an interior NUL byte.
22/// - [`Error::DepthExceeded`] if `value` nests deeper than the
23///   [depth limit](#depth-limit).
24///
25/// # Depth limit
26///
27/// A leaf can sit under at most 128 levels of containers. Each variant,
28/// array, maybe, tuple, and dict entry adds one level. A value of type `v`
29/// with 128 nested variants serializes. A value with 129 nested variants
30/// returns [`Error::DepthExceeded`].
31///
32/// [`from_bytes`] has the same limit, so it accepts each value that
33/// `to_bytes` accepts.
34///
35/// [`from_bytes`]: crate::from_bytes
36pub fn to_bytes(ty: &Type, value: &Value) -> Result<Vec<u8>> {
37    let mut buf = Vec::new();
38    serialize(&mut buf, ty, value, 0)?;
39    Ok(buf)
40}
41
42/// Serializes one value at the current buffer position.
43///
44/// The function computes alignment from absolute buffer positions. The
45/// top-level value starts at 0. Each container starts at a multiple of its
46/// own alignment. That alignment is at least the alignment of each member,
47/// so the absolute padding and the container-relative padding are equal.
48///
49/// `depth` counts container nesting the same way as the parser. Both use
50/// [`MAX_VALUE_DEPTH`], so the parser accepts each value that the serializer
51/// accepts.
52fn serialize(buf: &mut Vec<u8>, ty: &Type, value: &Value, depth: usize) -> Result<()> {
53    if depth > MAX_VALUE_DEPTH {
54        return Err(Error::DepthExceeded);
55    }
56    match (ty, value) {
57        // Scalar and string leaves use the encoding of the typed encoders.
58        // That encoding includes the interior-NUL check. The `Value` path
59        // only unwraps the leaf.
60        (Type::Bool, Value::Bool(b)) => b.encode(buf)?,
61        (Type::Byte, Value::Byte(b)) => b.encode(buf)?,
62        (Type::I16, Value::I16(x)) => buf.extend_from_slice(&x.to_le_bytes()),
63        (Type::U16, Value::U16(x)) => buf.extend_from_slice(&x.to_le_bytes()),
64        (Type::I32 | Type::Handle, Value::I32(x)) => buf.extend_from_slice(&x.to_le_bytes()),
65        (Type::U32, Value::U32(x)) => x.encode(buf)?,
66        (Type::I64, Value::I64(x)) => buf.extend_from_slice(&x.to_le_bytes()),
67        (Type::U64, Value::U64(x)) => x.encode(buf)?,
68        (Type::Double, Value::Double(bits)) => buf.extend_from_slice(&bits.to_le_bytes()),
69        (Type::Str | Type::ObjectPath | Type::Signature, Value::Str(s)) => {
70            s.as_str().encode(buf)?;
71        }
72        (Type::Maybe(elem), Value::Maybe(inner)) => {
73            // `Nothing` is the empty byte sequence. `Just` is the bytes of the
74            // element. If the element is variable-size, one zero byte follows
75            // the element bytes. This byte tells `Nothing` and `Just` apart.
76            if let Some(child) = inner {
77                serialize(buf, elem, child, depth + 1)?;
78                if elem.fixed_size().is_none() {
79                    buf.push(0);
80                }
81            }
82        }
83        (Type::Array(elem), Value::Bytes(b)) if **elem == Type::Byte => {
84            b.as_slice().encode(buf)?;
85        }
86        (Type::Array(elem), Value::Array(items)) if **elem != Type::Byte => {
87            serialize_array(buf, elem, items, depth)?;
88        }
89        (Type::Tuple(members), Value::Tuple(items)) => {
90            serialize_struct(buf, ty, members.iter(), items, depth)?;
91        }
92        (Type::DictEntry(key, val), Value::Tuple(items)) => {
93            serialize_struct(buf, ty, [&**key, &**val].into_iter(), items, depth)?;
94        }
95        (Type::Variant, Value::Variant(inner)) => {
96            let (child_ty, child) = &**inner;
97            // The buffer is 8-aligned here because the alignment of a variant
98            // is 8. This alignment satisfies the alignment of any child.
99            serialize(buf, child_ty, child, depth + 1)?;
100            buf.push(0);
101            buf.extend_from_slice(child_ty.signature().as_bytes());
102        }
103        _ => {
104            return Err(Error::TypeMismatch {
105                expected: ty.signature(),
106                found: value.kind(),
107            });
108        }
109    }
110    Ok(())
111}
112
113fn serialize_array(buf: &mut Vec<u8>, elem: &Type, items: &[Value], depth: usize) -> Result<()> {
114    write_array(
115        buf,
116        elem.alignment(),
117        elem.fixed_size().is_some(),
118        items.len(),
119        |buf, i| serialize(buf, elem, &items[i], depth + 1),
120    )
121}
122
123/// Serializes a tuple or a dict entry.
124fn serialize_struct<'t>(
125    buf: &mut Vec<u8>,
126    whole: &Type,
127    members: impl ExactSizeIterator<Item = &'t Type>,
128    items: &[Value],
129    depth: usize,
130) -> Result<()> {
131    let n = members.len();
132    if items.len() != n {
133        return Err(Error::TypeMismatch {
134            expected: whole.signature(),
135            found: "tuple of a different arity",
136        });
137    }
138    if n == 0 {
139        buf.push(0);
140        return Ok(());
141    }
142    let mut writer = TupleWriter::new(buf);
143    let last = n - 1;
144    for (i, (member_ty, item)) in members.zip(items).enumerate() {
145        writer.field_dyn(
146            member_ty.alignment(),
147            member_ty.fixed_size(),
148            i == last,
149            |buf| serialize(buf, member_ty, item, depth + 1),
150        )?;
151    }
152    writer.finish(whole.fixed_size());
153    Ok(())
154}
155
156/// Returns the size in bytes of each framing offset of a container.
157///
158/// `data_len` is the size of the container data, and `n_offsets` is the
159/// number of framing offsets. The result is the smallest size `z` whose range
160/// covers the total size of the container, `data_len + n_offsets * z`:
161///
162/// - 1 covers it if `data_len + n_offsets` is at most `0xFF`.
163/// - 2 covers it if `data_len + n_offsets * 2` is at most `0xFFFF`.
164/// - 4 covers it if `data_len + n_offsets * 4` is at most `0xFFFF_FFFF`.
165/// - 8 covers every other total size.
166///
167/// A reader derives the same size from the total size with
168/// [`offset_size_for`], so the writer and the reader agree.
169///
170/// With this function and [`write_offset`], a caller can write the framing of
171/// a container that is too large to buffer. An example is a static-delta part
172/// payload, whose two trailing byte arrays stream from disk. When the caller
173/// knows the length of each member, it can write the framing.
174///
175/// [`offset_size_for`]: crate::offset_size_for
176pub fn choose_offset_size(data_len: usize, n_offsets: usize) -> usize {
177    for z in [1usize, 2, 4] {
178        if data_len + n_offsets * z <= offset_max(z) {
179            return z;
180        }
181    }
182    8
183}
184
185pub(crate) fn offset_max(z: usize) -> usize {
186    match z {
187        1 => 0xFF,
188        2 => 0xFFFF,
189        4 => 0xFFFF_FFFF,
190        _ => usize::MAX,
191    }
192}
193
194/// Appends one framing offset of width `z`.
195///
196/// `value` is the end of a member, counted from the start of the container.
197/// The function writes the low `z` bytes of `value` in little-endian byte
198/// order. [`choose_offset_size`] gives the width `z`.
199///
200/// The offsets of a container follow its data. A tuple has its offsets in
201/// reverse member order. An array has its offsets in member order.
202///
203/// # Panics
204///
205/// Panics if `z` is more than the size of `usize` in bytes: 8 on a 64-bit
206/// target, 4 on a 32-bit target.
207pub fn write_offset(buf: &mut Vec<u8>, value: usize, z: usize) {
208    buf.extend_from_slice(&value.to_le_bytes()[..z]);
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    fn ser(sig: &str, value: &Value) -> Vec<u8> {
216        to_bytes(&Type::parse(sig).unwrap(), value).unwrap()
217    }
218
219    #[test]
220    fn scalars() {
221        assert_eq!(ser("y", &Value::Byte(0xab)), [0xab]);
222        assert_eq!(ser("b", &Value::Bool(true)), [1]);
223        assert_eq!(ser("b", &Value::Bool(false)), [0]);
224        assert_eq!(ser("u", &Value::U32(0x0102_0304)), [4, 3, 2, 1]);
225        assert_eq!(
226            ser("t", &Value::U64(0x0102_0304_0506_0708)),
227            [8, 7, 6, 5, 4, 3, 2, 1]
228        );
229        assert_eq!(ser("s", &Value::Str("hi".into())), b"hi\0");
230    }
231
232    #[test]
233    fn dirmeta_layout() {
234        // (uuua(ayay)) with uid 0, gid 0, mode 0o40755 in big-endian, and no
235        // xattrs. The value has three fixed u32 members and an empty final
236        // array. It is 12 bytes and has no framing offsets. The bytes match
237        // the golden dirmeta fixture.
238        let value = Value::Tuple(vec![
239            Value::U32(0),
240            Value::U32(0),
241            Value::U32(0o40755u32.swap_bytes()),
242            Value::Array(vec![]),
243        ]);
244        assert_eq!(
245            ser("(uuua(ayay))", &value),
246            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x41, 0xed]
247        );
248    }
249
250    #[test]
251    fn string_array_framing() {
252        let value = Value::Array(vec!["foo".into(), "bar".into()]);
253        assert_eq!(ser("as", &value), b"foo\0bar\0\x04\x08");
254    }
255
256    #[test]
257    fn empty_containers() {
258        assert_eq!(ser("as", &Value::Array(vec![])), Vec::<u8>::new());
259        assert_eq!(ser("ay", &Value::Bytes(vec![])), Vec::<u8>::new());
260        assert_eq!(ser("a{sv}", &Value::Array(vec![])), Vec::<u8>::new());
261        assert_eq!(ser("()", &Value::Tuple(vec![])), [0]);
262    }
263
264    #[test]
265    fn dict_with_one_entry() {
266        // {"version": <"1">}: the key "version\0" fills bytes 0..8. The
267        // variant member is 8-aligned. The variant is "1\0" + NUL + "s". The
268        // framing offset of the entry is the end of the key (8). The framing
269        // offset of the array is the end of the entry (13).
270        let entry = Value::Tuple(vec![
271            "version".into(),
272            Value::variant(Type::Str, "1".into()),
273        ]);
274        assert_eq!(
275            ser("a{sv}", &Value::Array(vec![entry])),
276            b"version\x001\0\0s\x08\x0d"
277        );
278    }
279
280    #[test]
281    fn variable_tuple_with_fixed_final_member() {
282        // (su): the end of the string needs a framing offset. The trailing
283        // u32 needs no framing offset. Padding to the u32 alignment separates
284        // the two members.
285        let value = Value::Tuple(vec!["abc".into(), Value::U32(5)]);
286        assert_eq!(ser("(su)", &value), b"abc\0\x05\0\0\0\x04");
287    }
288
289    #[test]
290    fn fixed_element_array_packs_without_offsets() {
291        let value = Value::Array(vec![
292            Value::Tuple(vec![Value::U32(1), Value::U32(2), Value::U32(3)]),
293            Value::Tuple(vec![Value::U32(4), Value::U32(5), Value::U32(6)]),
294        ]);
295        assert_eq!(
296            ser("a(uuu)", &value),
297            [
298                1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0
299            ]
300        );
301    }
302
303    #[test]
304    fn fixed_tuple_end_padding() {
305        let value = Value::Tuple(vec![Value::U64(1), Value::Byte(2)]);
306        assert_eq!(
307            ser("(ty)", &value),
308            [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]
309        );
310    }
311
312    #[test]
313    fn two_byte_offsets_past_255_bytes() {
314        // 30 nine-byte strings give 270 data bytes. This size forces 2-byte
315        // framing offsets, so the array is 270 + 30 * 2 bytes.
316        let items: Vec<Value> = (0..30)
317            .map(|i| Value::Str(format!("string{i:02}")))
318            .collect();
319        let bytes = ser("as", &Value::Array(items));
320        assert_eq!(bytes.len(), 270 + 60);
321        // The first framing offset is the end of the first 9-byte element.
322        // It is 2 bytes little-endian.
323        assert_eq!(&bytes[270..272], &9u16.to_le_bytes());
324        // The last framing offset is the end of the data area.
325        assert_eq!(&bytes[328..330], &270u16.to_le_bytes());
326    }
327
328    #[test]
329    fn rejects_value_depth_bomb() {
330        // The encode path accepts at most 128 nested variants. 129 nested
331        // variants exceed MAX_VALUE_DEPTH.
332        let mut value = Value::variant(Type::Byte, Value::Byte(1));
333        for _ in 0..127 {
334            value = Value::variant(Type::Variant, value);
335        }
336        let v = Type::parse("v").unwrap();
337        assert!(to_bytes(&v, &value).is_ok());
338        value = Value::variant(Type::Variant, value);
339        assert_eq!(to_bytes(&v, &value), Err(Error::DepthExceeded));
340    }
341
342    #[test]
343    fn rejects_interior_nul_in_string() {
344        let err = to_bytes(&Type::parse("s").unwrap(), &Value::Str("a\0b".into())).unwrap_err();
345        assert_eq!(
346            err,
347            Error::InvalidValue("string contains an interior NUL byte")
348        );
349    }
350
351    #[test]
352    fn rejects_mismatched_value() {
353        let err = to_bytes(&Type::parse("u").unwrap(), &Value::Str("x".into())).unwrap_err();
354        assert!(matches!(err, Error::TypeMismatch { .. }));
355        // A value of type ay must be Bytes. An Array of Byte is a mismatch.
356        let err = to_bytes(
357            &Type::parse("ay").unwrap(),
358            &Value::Array(vec![Value::Byte(1)]),
359        )
360        .unwrap_err();
361        assert!(matches!(err, Error::TypeMismatch { .. }));
362        let err = to_bytes(
363            &Type::parse("(uu)").unwrap(),
364            &Value::Tuple(vec![Value::U32(1)]),
365        )
366        .unwrap_err();
367        assert!(matches!(err, Error::TypeMismatch { .. }));
368    }
369}