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
use core::marker::PhantomData;
use core::mem::{MaybeUninit, align_of, size_of, size_of_val, transmute};
use core::ptr::NonNull;
use crate::buf;
use crate::traits::{ZeroCopy, ZeroSized};
/// A struct padder as provided to the [`ZeroCopy::pad`] method.
///
/// This knows how to find and initialize padding regions in `repr(C)` types,
/// and provides a builder-like API to doing so.
#[must_use = "For the writer to have an effect on `OwnedBuf` you must call `Padder::remaining` / `Padder::remaining_unsized`"]
pub struct Padder<'a, T: ?Sized> {
data: NonNull<MaybeUninit<u8>>,
offset: usize,
_marker: PhantomData<&'a mut T>,
}
impl<'a, T: ?Sized> Padder<'a, T> {
#[inline]
pub(crate) fn new(data: NonNull<MaybeUninit<u8>>) -> Self {
Self {
data,
offset: 0,
_marker: PhantomData,
}
}
/// Indicate that this validate is transparent over `U`.
//
/// # Safety
///
/// This is only allowed if `T` is `#[repr(transparent)]` over `U`.
#[inline]
pub unsafe fn transparent<U>(&mut self) -> &mut Padder<'a, U> {
unsafe { transmute(self) }
}
/// Pad around the given field with zeros.
///
/// Note that this is necessary to do correctly in order to satisfy the
/// safety requirements by [`remaining()`].
///
/// This is typically not called directly, but rather is implemented by the
/// [`ZeroCopy`] derive.
///
/// [`remaining()`]: Self::remaining
/// [`ZeroCopy`]: derive@crate::ZeroCopy
///
/// # Safety
///
/// The caller must ensure that the field type `F` is an actual field in
/// order in the struct being padded.
#[inline]
pub unsafe fn pad<F>(&mut self)
where
F: ZeroCopy,
{
unsafe {
self.pad_with::<F>(align_of::<F>());
}
}
/// Pad around the given field with zeros for a struct marked
/// `#[repr(packed(align))]`.
///
/// The field is aligned to `min(align, align_of::<F>())`, which is the
/// alignment the compiler uses for fields in a packed struct.
///
/// Note that this is necessary to do correctly in order to satisfy the
/// safety requirements by [`remaining()`].
///
/// This is typically not called directly, but rather is implemented by the
/// [`ZeroCopy`] derive.
///
/// [`remaining()`]: Self::remaining
/// [`ZeroCopy`]: derive@crate::ZeroCopy
///
/// # Safety
///
/// The caller must ensure that the field type `F` is an actual field in
/// order in the struct being padded and that `align` matches the argument
/// provided to `#[repr(packed)]` (note that empty means 1). `align` must
/// be a power of two.
#[inline]
pub unsafe fn pad_with<F>(&mut self, align: usize)
where
F: ZeroCopy,
{
unsafe {
let align = align.min(align_of::<F>());
let count = buf::padding_to(self.offset, align);
// zero out padding.
self.data.as_ptr().add(self.offset).write_bytes(0, count);
self.offset += count;
if F::PADDED {
let ptr = NonNull::new_unchecked(self.data.as_ptr().add(self.offset));
let mut padder = Padder::new(ptr);
F::pad(&mut padder);
padder.remaining();
}
self.offset += size_of::<F>();
}
}
/// Pad up to an ignored zero-sized field `F`.
///
/// Zero-sized fields can have an alignment larger than 1, in which case
/// they affect the offset of the fields that follow them.
///
/// This is typically not called directly, but rather is implemented by the
/// [`ZeroCopy`] derive.
///
/// [`ZeroCopy`]: derive@crate::ZeroCopy
///
/// # Safety
///
/// The caller must ensure that the field type `F` is an actual field in
/// order in the struct being padded.
#[inline]
pub unsafe fn pad_zero_sized<F>(&mut self)
where
F: ZeroSized,
{
unsafe {
self.pad_zero_sized_with::<F>(align_of::<F>());
}
}
/// Pad up to an ignored zero-sized field `F` in a struct marked
/// `#[repr(packed(align))]`.
///
/// The field is aligned to `min(align, align_of::<F>())`.
///
/// This is typically not called directly, but rather is implemented by the
/// [`ZeroCopy`] derive.
///
/// [`ZeroCopy`]: derive@crate::ZeroCopy
///
/// # Safety
///
/// The caller must ensure that the field type `F` is an actual field in
/// order in the struct being padded and that `align` matches the argument
/// provided to `#[repr(packed)]` (note that empty means 1). `align` must
/// be a power of two.
#[inline]
pub unsafe fn pad_zero_sized_with<F>(&mut self, align: usize)
where
F: ZeroSized,
{
unsafe {
let count = buf::padding_to(self.offset, align.min(align_of::<F>()));
// zero out padding.
self.data.as_ptr().add(self.offset).write_bytes(0, count);
self.offset += count;
}
}
/// Specific method to both pad for a discriminant and load it
/// simultaneously for inspection.
///
/// # Safety
///
/// The caller must ensure that the field type `D` is the actual type of the
/// discriminant first in order in the enum being padded and that `D` is a
/// primitive that does not contain any interior padding.
#[inline]
pub unsafe fn pad_discriminant<D>(&mut self) -> D
where
D: ZeroCopy,
{
unsafe {
let count = buf::padding_to(self.offset, align_of::<D>());
// zero out padding.
self.data.as_ptr().add(self.offset).write_bytes(0, count);
let at = self.offset + count;
let value = self.data.as_ptr().add(at).cast::<D>().read_unaligned();
self.offset = at + size_of::<D>();
value
}
}
/// Finish writing the current buffer.
///
/// This is typically not called directly, but rather is implemented by the
/// [`ZeroCopy`] derive.
///
/// [`ZeroCopy`]: derive@crate::ZeroCopy
///
/// # Safety
///
/// Before calling `remaining()`, the caller must ensure that they've called
/// [`pad::<F>()`] *in order* for every field in a struct being serialized
/// where `F` is the type of the field. Otherwise we might not have written
/// the necessary padding to ensure that all bytes related to the struct are
/// initialized. Failure to do so would result in undefined behavior.
///
/// Fields which are [`ZeroSized`] must be padded with
/// [`pad_zero_sized::<F>()`] unless their alignment is 1, since they can
/// affect the offset of the fields that follow them.
///
/// [`pad::<F>()`]: Self::pad
/// [`pad_zero_sized::<F>()`]: Self::pad_zero_sized
/// [`ZeroSized`]: crate::traits::ZeroSized
#[inline]
pub unsafe fn remaining(self)
where
T: Sized,
{
debug_assert!(
self.offset <= size_of::<T>(),
"padded fields extend past the end of the type"
);
unsafe {
let count = size_of::<T>() - self.offset;
self.data.as_ptr().add(self.offset).write_bytes(0, count);
}
}
/// Finalize remaining padding based on the size of an unsized value.
#[inline]
pub(crate) unsafe fn remaining_unsized(self, value: &T) {
debug_assert!(
self.offset <= size_of_val(value),
"padded fields extend past the end of the value"
);
unsafe {
let count = size_of_val(value) - self.offset;
self.data.as_ptr().add(self.offset).write_bytes(0, count);
}
}
}
#[cfg(test)]
mod tests {
use std::mem::size_of;
use anyhow::Result;
use crate::{OwnedBuf, ZeroCopy, buf};
#[test]
fn ensure_padding() -> Result<()> {
#[derive(Debug, PartialEq, Eq, ZeroCopy)]
#[repr(C)]
#[zero_copy(crate)]
struct ZeroPadded(u8, u16, u64);
let padded = ZeroPadded(
0x01u8.to_be(),
0x0203u16.to_be(),
0x0405060708090a0bu64.to_be(),
);
let mut buf = OwnedBuf::new();
// Note: You're responsible for ensuring that the buffer has enough
// capacity.
buf.reserve(size_of::<ZeroPadded>())?;
// SAFETY: We do not pad beyond known fields and are making sure to
// initialize all of the buffer.
unsafe {
buf::store_unaligned(buf.as_nonnull(), &padded);
buf.advance(size_of::<ZeroPadded>());
}
// Note: The bytes are explicitly convert to big-endian encoding above.
assert_eq!(
buf.as_slice(),
&[1, 0, 2, 3, 0, 0, 0, 0, 4, 5, 6, 7, 8, 9, 10, 11]
);
Ok(())
}
}