Skip to content

Commit 1509393

Browse files
authored
Merge pull request #171 from wedsonaf/write
Add `UserSlicePtrWriter::write`.
2 parents 858b23c + ef7b3ff commit 1509393

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

rust/kernel/user_ptr.rs

+33
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,32 @@ unsafe impl ReadableFromBytes for i32 {}
4646
unsafe impl ReadableFromBytes for i64 {}
4747
unsafe impl ReadableFromBytes for isize {}
4848

49+
/// Specifies that a type is safely writable to byte slices.
50+
///
51+
/// This means that we don't read undefined values (which leads to UB) in preparation for writing
52+
/// to the byte slice. It also ensures that no potentially sensitive information is leaked into the
53+
/// byte slices.
54+
///
55+
/// # Safety
56+
///
57+
/// A type must not include padding bytes and must be fully initialised to safely implement
58+
/// [`WritableToBytes`] (i.e., it doesn't contain [`MaybeUninit`] fields). A composition of
59+
/// writable types in a structure is not necessarily writable because it may result in padding
60+
/// bytes.
61+
pub unsafe trait WritableToBytes {}
62+
63+
// SAFETY: Initialised instances of the following types have no uninitialised portions.
64+
unsafe impl WritableToBytes for u8 {}
65+
unsafe impl WritableToBytes for u16 {}
66+
unsafe impl WritableToBytes for u32 {}
67+
unsafe impl WritableToBytes for u64 {}
68+
unsafe impl WritableToBytes for usize {}
69+
unsafe impl WritableToBytes for i8 {}
70+
unsafe impl WritableToBytes for i16 {}
71+
unsafe impl WritableToBytes for i32 {}
72+
unsafe impl WritableToBytes for i64 {}
73+
unsafe impl WritableToBytes for isize {}
74+
4975
/// A reference to an area in userspace memory, which can be either
5076
/// read-only or read-write.
5177
///
@@ -246,4 +272,11 @@ impl UserSlicePtrWriter {
246272
self.1 -= len;
247273
Ok(())
248274
}
275+
276+
/// Writes the contents of the given data into the user slice.
277+
pub fn write<T: WritableToBytes>(&mut self, data: &T) -> KernelResult<()> {
278+
// SAFETY: The input buffer is valid as it's coming from a live
279+
// reference to a type that implements `WritableToBytes`.
280+
unsafe { self.write_raw(data as *const T as _, size_of::<T>()) }
281+
}
249282
}

0 commit comments

Comments
 (0)