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
//! Validation implementations for core types.

use crate::{
    core_impl::{
        range::{ArchivedRange, ArchivedRangeInclusive},
        ArchivedOption, ArchivedOptionTag, ArchivedOptionVariantSome, ArchivedRef, ArchivedSlice,
        ArchivedStringSlice,
    },
    offset_of,
    validation::{ArchiveContext, ArchiveMemoryError},
    RelPtr,
};
use bytecheck::{CheckBytes, StructCheckError, Unreachable};
use core::{fmt, str};
use std::error::Error;

/// Errors that can occur while checking an [`ArchivedRef`].
#[derive(Debug)]
pub enum ArchivedRefError<T> {
    /// A memory error occurred
    MemoryError(ArchiveMemoryError),
    /// An error occurred while checking the bytes of the target type
    CheckBytes(T),
}

impl<T: fmt::Display> fmt::Display for ArchivedRefError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArchivedRefError::MemoryError(e) => write!(f, "archived ref memory error: {}", e),
            ArchivedRefError::CheckBytes(e) => write!(f, "archived ref check error: {}", e),
        }
    }
}

impl<T: fmt::Debug + fmt::Display> Error for ArchivedRefError<T> {}

impl<T> From<ArchiveMemoryError> for ArchivedRefError<T> {
    fn from(e: ArchiveMemoryError) -> Self {
        Self::MemoryError(e)
    }
}

impl<T> From<Unreachable> for ArchivedRefError<T> {
    fn from(_: Unreachable) -> Self {
        unreachable!();
    }
}

impl<T: CheckBytes<ArchiveContext>> CheckBytes<ArchiveContext> for ArchivedRef<T> {
    type Error = ArchivedRefError<T::Error>;

    unsafe fn check_bytes<'a>(
        bytes: *const u8,
        context: &mut ArchiveContext,
    ) -> Result<&'a Self, Self::Error> {
        let rel_ptr = RelPtr::check_bytes(bytes, context)?;
        let target = context.claim::<T>(bytes, rel_ptr.offset(), 1)?;
        T::check_bytes(target, context).map_err(ArchivedRefError::CheckBytes)?;
        Ok(&*bytes.cast())
    }
}

/// Errors that can occur while checking an [`ArchivedSlice`].
#[derive(Debug)]
pub enum ArchivedSliceError<T> {
    /// A memory error occurred
    MemoryError(ArchiveMemoryError),
    /// An error occurred while checking the bytes of an item of the target type
    CheckBytes(usize, T),
}

impl<T: fmt::Display> fmt::Display for ArchivedSliceError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArchivedSliceError::MemoryError(e) => write!(f, "archived slice memory error: {}", e),
            ArchivedSliceError::CheckBytes(index, e) => {
                write!(f, "archived slice index {} check error: {}", index, e)
            }
        }
    }
}

impl<T: fmt::Debug + fmt::Display> Error for ArchivedSliceError<T> {}

impl<T> From<ArchiveMemoryError> for ArchivedSliceError<T> {
    fn from(e: ArchiveMemoryError) -> Self {
        Self::MemoryError(e)
    }
}

impl<T> From<Unreachable> for ArchivedSliceError<T> {
    fn from(_: Unreachable) -> Self {
        unreachable!();
    }
}

impl<T: CheckBytes<ArchiveContext>> CheckBytes<ArchiveContext> for ArchivedSlice<T> {
    type Error = ArchivedSliceError<T::Error>;

    unsafe fn check_bytes<'a>(
        bytes: *const u8,
        context: &mut ArchiveContext,
    ) -> Result<&'a Self, Self::Error> {
        let rel_ptr = RelPtr::check_bytes(bytes.add(offset_of!(Self, ptr)), context)?;
        let len = *u32::check_bytes(bytes.add(offset_of!(Self, len)), context)? as usize;
        let target = context.claim::<T>(bytes, rel_ptr.offset(), len)?;
        for i in 0..len {
            T::check_bytes(target.add(i * core::mem::size_of::<T>()), context)
                .map_err(|e| ArchivedSliceError::CheckBytes(i, e))?;
        }
        Ok(&*bytes.cast())
    }
}

/// Errors that can occur while checking an [`ArchivedStringSlice`].
#[derive(Debug)]
pub enum ArchivedStringSliceError {
    /// A memory error occurred
    MemoryError(ArchiveMemoryError),
    /// The bytes of the string were invalid UTF-8
    InvalidUtf8(str::Utf8Error),
}

impl fmt::Display for ArchivedStringSliceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArchivedStringSliceError::MemoryError(e) => {
                write!(f, "archived string slice memory error: {}", e)
            }
            ArchivedStringSliceError::InvalidUtf8(e) => {
                write!(f, "archived string slice contained invalid UTF-8: {}", e)
            }
        }
    }
}

impl Error for ArchivedStringSliceError {}

impl From<ArchiveMemoryError> for ArchivedStringSliceError {
    fn from(e: ArchiveMemoryError) -> Self {
        Self::MemoryError(e)
    }
}

impl From<Unreachable> for ArchivedStringSliceError {
    fn from(_: Unreachable) -> Self {
        unreachable!();
    }
}

impl CheckBytes<ArchiveContext> for ArchivedStringSlice {
    type Error = ArchivedStringSliceError;

    unsafe fn check_bytes<'a>(
        bytes: *const u8,
        context: &mut ArchiveContext,
    ) -> Result<&'a Self, Self::Error> {
        let slice = ArchivedSlice::<u8>::check_bytes(bytes, context).map_err(|e| match e {
            ArchivedSliceError::MemoryError(e) => e,
            ArchivedSliceError::CheckBytes(..) => unreachable!(),
        })?;
        str::from_utf8(&**slice).map_err(ArchivedStringSliceError::InvalidUtf8)?;
        Ok(&*bytes.cast())
    }
}

/// Errors that can occur while checking an [`ArchivedOption`].
#[derive(Debug)]
pub enum ArchivedOptionError<T> {
    /// The option had an invalid tag
    InvalidTag(u8),
    /// An error occurred while checking the bytes of the target type
    CheckBytes(T),
}

impl<T: fmt::Display> fmt::Display for ArchivedOptionError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ArchivedOptionError::InvalidTag(tag) => {
                write!(f, "archived option had invalid tag: {}", tag)
            }
            ArchivedOptionError::CheckBytes(e) => write!(f, "archived option check error: {}", e),
        }
    }
}

impl<T: fmt::Debug + fmt::Display> Error for ArchivedOptionError<T> {}

impl<T> From<Unreachable> for ArchivedOptionError<T> {
    fn from(_: Unreachable) -> Self {
        unreachable!();
    }
}

impl ArchivedOptionTag {
    const TAG_NONE: u8 = ArchivedOptionTag::None as u8;
    const TAG_SOME: u8 = ArchivedOptionTag::Some as u8;
}

impl<C, T: CheckBytes<C>> CheckBytes<C> for ArchivedOption<T> {
    type Error = ArchivedOptionError<T::Error>;

    unsafe fn check_bytes<'a>(bytes: *const u8, context: &mut C) -> Result<&'a Self, Self::Error> {
        let tag = *u8::check_bytes(bytes, context)?;
        match tag {
            ArchivedOptionTag::TAG_NONE => (),
            ArchivedOptionTag::TAG_SOME => {
                T::check_bytes(
                    bytes.add(offset_of!(ArchivedOptionVariantSome<T>, 1)),
                    context,
                )
                .map_err(ArchivedOptionError::CheckBytes)?;
            }
            _ => return Err(ArchivedOptionError::InvalidTag(tag)),
        }
        Ok(&*bytes.cast())
    }
}

impl<C, T: CheckBytes<C>> CheckBytes<C> for ArchivedRange<T> {
    type Error = StructCheckError;

    unsafe fn check_bytes<'a>(bytes: *const u8, context: &mut C) -> Result<&'a Self, Self::Error> {
        T::check_bytes(bytes.add(offset_of!(ArchivedRange<T>, start)), context).map_err(|e| {
            StructCheckError {
                field_name: "start",
                inner: Box::new(e),
            }
        })?;
        T::check_bytes(bytes.add(offset_of!(ArchivedRange<T>, end)), context).map_err(|e| {
            StructCheckError {
                field_name: "end",
                inner: Box::new(e),
            }
        })?;
        Ok(&*bytes.cast())
    }
}

impl<C, T: CheckBytes<C>> CheckBytes<C> for ArchivedRangeInclusive<T> {
    type Error = StructCheckError;

    unsafe fn check_bytes<'a>(bytes: *const u8, context: &mut C) -> Result<&'a Self, Self::Error> {
        T::check_bytes(
            bytes.add(offset_of!(ArchivedRangeInclusive<T>, start)),
            context,
        )
        .map_err(|e| StructCheckError {
            field_name: "start",
            inner: Box::new(e),
        })?;
        T::check_bytes(
            bytes.add(offset_of!(ArchivedRangeInclusive<T>, end)),
            context,
        )
        .map_err(|e| StructCheckError {
            field_name: "end",
            inner: Box::new(e),
        })?;
        Ok(&*bytes.cast())
    }
}