selinux/policy/
parser.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright 2023 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::fmt::Debug;
use std::io::{Cursor, Seek as _, SeekFrom};
use std::ops::Deref;
use zerocopy::{FromBytes, Immutable, KnownLayout, Ref, SplitByteSlice, Unaligned};

/// Trait for a cursor that can emit a slice of "remaining" data, and advance forward.
trait ParseCursor: Sized {
    /// The inner representation that owns the underlying data.
    type Inner;

    /// The error returned when seeking forward fails on this cursor.
    type Error;

    /// Returns a slice of remaining data.
    fn remaining_slice(&self) -> &[u8];

    /// Returns the number of bytes remaining to be parsed by this [`ParseCursor`].
    fn len(&self) -> usize;

    /// Seeks forward by `num_bytes`, returning a `Self::Error` if seeking fails.
    fn seek_forward(&mut self, num_bytes: usize) -> Result<(), Self::Error>;

    /// Consumes self and returns the inner representation of the complete parse input.
    #[allow(dead_code)]
    fn into_inner(self) -> Self::Inner;
}

impl<T: AsRef<[u8]>> ParseCursor for Cursor<T> {
    type Inner = T;
    type Error = std::io::Error;

    fn remaining_slice(&self) -> &[u8] {
        let s: &[u8] = self.get_ref().as_ref();
        let p = self.position() as usize;
        &s[p..]
    }

    fn len(&self) -> usize {
        let position = self.position() as usize;
        self.get_ref().as_ref().len() - position
    }

    fn seek_forward(&mut self, num_bytes: usize) -> Result<(), Self::Error> {
        self.seek(SeekFrom::Current(num_bytes as i64)).map(|_| ())
    }

    #[allow(dead_code)]
    fn into_inner(self) -> Self::Inner {
        self.into_inner()
    }
}

/// A strategy for parsing data. Parsed structures that may contain references to parsed data are
/// generally of the form:
///
/// ```rust,ignore
/// type ParserOutput<PS: ParseStrategy> {
///     ref_or_value_t: PS::Output<T>,
///     // ...
/// }
/// ```
///
/// The above pattern allows [`ParseStrategy`] implementations to dictate how values are stored (by
/// copied value, or reference to parser input data).
pub trait ParseStrategy: Debug + PartialEq + Sized {
    /// Type of input supported by this [`ParseStrategy`].
    type Input;

    /// Type of successfully parsed output from `Self::parse()`.
    type Output<T: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>: Debug
        + PartialEq;

    /// Type of successfully parsed output from `Self::parse_slice()`.
    type Slice<T: Debug + FromBytes + Immutable + PartialEq + Unaligned>: Debug + PartialEq;

    /// Parses a `Self::Output<T>` from the next bytes underlying `self`. If the parse succeeds,
    /// then return `(Some(output), self)` after advancing past the parsed bytes. Otherwise, return
    /// `None` without advancing past the parsed bytes.
    fn parse<T: Clone + Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>(
        self,
    ) -> Option<(Self::Output<T>, Self)>;

    /// Parses a `Self::Slice<T>` of `count` elements from the next bytes underlying `self`. If the
    /// parse succeeds, then return `(Some(slice), self)` after advancing past the parsed bytes.
    /// Otherwise, return `None` without advancing past the parsed bytes.
    fn parse_slice<T: Clone + Debug + FromBytes + Immutable + PartialEq + Unaligned>(
        self,
        count: usize,
    ) -> Option<(Self::Slice<T>, Self)>;

    /// Dereferences borrow of `Self::Output<T>` as borrow of `T`.
    fn deref<'a, T: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>(
        output: &'a Self::Output<T>,
    ) -> &'a T;

    /// Dereferences borrow of `Self::Slice<T>` as borrow of `[T]`.
    fn deref_slice<'a, T: Debug + FromBytes + Immutable + PartialEq + Unaligned>(
        slice: &'a Self::Slice<T>,
    ) -> &'a [T];

    /// Returns the number of bytes remaining to be parsed by this [`ParseStrategy`].
    fn len(&self) -> usize;

    /// Returns the complete parse input being consumed by this strategy.
    fn into_inner(self) -> Self::Input;
}

/// A [`ParseStrategy`] that produces [`Ref<B, T>`].
///
/// This strategy is zero-copy, but one consequence is that the parser input and output cannot be
/// retained outside the lexical scope from which the parser input was borrowed. For example, the
/// following will not compile:
///
/// ```rust,ignore
/// fn do_by_ref<'a, T: zerocopy::FromBytes + zerocopy::Unaligned>() -> (
///     zerocopy::Ref<&'a [u8], T>, ByRef<&'a [u8]>,
/// ) {
///     let bytes: Vec<u8> = // ...
///     let parser = ByRef::new(bytes.as_slice());
///     parser.parse::<T>().unwrap()
/// }
/// ```
///
/// The above code induces the following error:
///
/// ```rust,ignore
/// error[E0515]: cannot return value referencing local variable `bytes`
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct ByRef<B: SplitByteSlice> {
    input: B,
    tail: B,
}

impl<B: SplitByteSlice + Clone> ByRef<B> {
    /// Returns a new [`ByRef`] that wraps `bytes_slice`.
    pub fn new(byte_slice: B) -> Self {
        Self { input: byte_slice.clone(), tail: byte_slice }
    }
}

impl<B: Debug + SplitByteSlice + PartialEq> ParseStrategy for ByRef<B> {
    type Input = B;
    type Output<T: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned> = Ref<B, T>;
    type Slice<T: Debug + FromBytes + Immutable + PartialEq + Unaligned> = Ref<B, [T]>;

    /// Returns a [`Ref<B, T>`] as the parsed output of the next bytes in the underlying
    /// [`ByteSlice`].
    fn parse<T: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>(
        self,
    ) -> Option<(Self::Output<T>, Self)> {
        let (output, tail) = Ref::from_prefix(self.tail).ok()?;
        Some((output, Self { input: self.input, tail }))
    }

    /// Returns a `Ref<B, [T]>` as the parsed output of the next bytes in the underlying
    /// [`ByteSlice`].
    fn parse_slice<T: Clone + Debug + FromBytes + Immutable + PartialEq + Unaligned>(
        self,
        num: usize,
    ) -> Option<(Self::Slice<T>, Self)> {
        let (slice, tail) = Ref::from_prefix_with_elems(self.tail, num).ok()?;
        Some((slice, Self { input: self.input, tail }))
    }

    fn deref<'a, T: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>(
        output: &'a Self::Output<T>,
    ) -> &'a T {
        output.deref() as &T
    }

    fn deref_slice<'a, T: Debug + FromBytes + Immutable + PartialEq + Unaligned>(
        slice: &'a Self::Slice<T>,
    ) -> &'a [T] {
        slice.deref() as &[T]
    }

    fn len(&self) -> usize {
        self.tail.len()
    }

    fn into_inner(self) -> Self::Input {
        self.input
    }
}

/// A [`ParseStrategy`] that produces (copied/cloned) `T`.
///
/// This strategy makes up to one copy of the parser input (in addition to parser output data
/// structures). It is intended to support use cases where the parser input and parser output must
/// be retained outside the lexical from which parsing is invoked. For example:
///
/// ```rust,ignore
/// fn do_by_value<
///     D: AsRef<[u8]> + Debug + PartialEq,
///     T: zerocopy::FromBytes + zerocopy::Unaligned,
/// >(
///     data: D,
/// ) -> (T, ByValue<D>) {
///     let parser = ByValue::new(data);
///     parser.parse::<T>().unwrap()
/// }
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct ByValue<T: AsRef<[u8]>>(Cursor<T>);

impl<T: AsRef<[u8]>> ByValue<T> {
    /// Returns a new [`ByValue`] that wraps `data` in a [`Cursor`] for parsing.
    pub fn new(data: T) -> Self {
        Self(Cursor::new(data))
    }
}

impl<T: AsRef<[u8]> + Debug + PartialEq> ParseStrategy for ByValue<T>
where
    Cursor<T>: Debug + ParseCursor + PartialEq,
{
    type Input = T;
    type Output<O: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned> = O;
    type Slice<S: Debug + FromBytes + Immutable + PartialEq + Unaligned> = Vec<S>;

    /// Returns an `P` as the parsed output of the next bytes in the underlying [`Cursor`] data.
    fn parse<P: Clone + Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>(
        mut self,
    ) -> Option<(Self::Output<P>, Self)> {
        let (output, _) = P::read_from_prefix(ParseCursor::remaining_slice(&self.0)).ok()?;
        if self.0.seek_forward(std::mem::size_of_val(&output)).is_err() {
            return None;
        }
        Some((output, self))
    }

    /// Returns a `Vec<T>` of `count` items as the parsed output of the next bytes in the underlying
    /// [`Cursor`] data.
    fn parse_slice<PS: Clone + Debug + FromBytes + Immutable + PartialEq + Unaligned>(
        mut self,
        count: usize,
    ) -> Option<(Self::Slice<PS>, Self)> {
        let (slice, _) =
            <[PS]>::ref_from_prefix_with_elems(ParseCursor::remaining_slice(&self.0), count)
                .ok()?;
        let size = std::mem::size_of_val(&slice);
        let slice = slice.to_owned();
        if self.0.seek_forward(size).is_err() {
            return None;
        }
        Some((slice, self))
    }

    fn deref<'a, D: Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned>(
        output: &'a Self::Output<D>,
    ) -> &'a D {
        output
    }

    fn deref_slice<'a, DS: Debug + FromBytes + Immutable + PartialEq + Unaligned>(
        slice: &'a Self::Slice<DS>,
    ) -> &'a [DS] {
        slice
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn into_inner(self) -> Self::Input {
        self.0.into_inner()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use zerocopy::little_endian as le;

    #[derive(Clone, Debug, KnownLayout, FromBytes, Immutable, PartialEq, Unaligned)]
    #[repr(C, packed)]
    struct SomeNumbers {
        a: u8,
        b: le::U32,
        c: le::U16,
        d: u8,
    }

    // Ensure that "return parser + parsed output" pattern works on `ByValue`.
    fn do_by_value<
        D: AsRef<[u8]> + Debug + PartialEq,
        T: Clone + Debug + FromBytes + KnownLayout + Immutable + PartialEq + Unaligned,
    >(
        data: D,
    ) -> (T, ByValue<D>) {
        let parser = ByValue::new(data);
        parser.parse::<T>().expect("some numbers")
    }
    fn do_slice_by_value<
        D: AsRef<[u8]> + Debug + PartialEq,
        T: Clone + Debug + FromBytes + Immutable + PartialEq + Unaligned,
    >(
        data: D,
        count: usize,
    ) -> (Vec<T>, ByValue<D>) {
        let parser = ByValue::new(data);
        parser.parse_slice::<T>(count).expect("some numbers")
    }

    #[test]
    fn by_ref_slice_u8_parse() {
        let bytes: Vec<u8> = (0..8).collect();
        let parser = ByRef::new(bytes.as_slice());
        let (some_numbers, parser) = parser.parse::<SomeNumbers>().expect("some numbers");
        assert_eq!(0, some_numbers.a);
        assert_eq!(7, some_numbers.d);
        assert_eq!(0, parser.tail.len());
    }

    #[test]
    fn by_ref_slice_u8_parse_slice() {
        let bytes: Vec<u8> = (0..24).collect();
        let parser = ByRef::new(bytes.as_slice());
        let (some_numbers, parser) = parser.parse_slice::<SomeNumbers>(3).expect("some numbers");
        assert_eq!(3, some_numbers.len());
        assert_eq!(0, some_numbers[0].a);
        assert_eq!(7, some_numbers[0].d);
        assert_eq!(8, some_numbers[1].a);
        assert_eq!(15, some_numbers[1].d);
        assert_eq!(16, some_numbers[2].a);
        assert_eq!(23, some_numbers[2].d);
        assert_eq!(0, parser.tail.len());
    }

    #[test]
    fn by_value_cursor_vec_u8() {
        let bytes: Vec<u8> = (0..8).collect();
        let (some_numbers, parser) = do_by_value::<_, SomeNumbers>(bytes);
        assert_eq!(0, some_numbers.a);
        assert_eq!(7, some_numbers.d);
        assert_eq!(8, parser.0.position());
        assert_eq!(8, parser.into_inner().len());
    }

    #[test]
    fn by_value_slice_u8_parse_slice() {
        let bytes: Vec<u8> = (0..24).collect();
        let (some_numbers, parser) = do_slice_by_value::<_, SomeNumbers>(bytes.as_slice(), 3);
        assert_eq!(3, some_numbers.len());
        assert_eq!(0, some_numbers[0].a);
        assert_eq!(7, some_numbers[0].d);
        assert_eq!(8, some_numbers[1].a);
        assert_eq!(15, some_numbers[1].d);
        assert_eq!(16, some_numbers[2].a);
        assert_eq!(23, some_numbers[2].d);
        assert_eq!(24, parser.into_inner().len());
    }
}