@@ -46,6 +46,32 @@ unsafe impl ReadableFromBytes for i32 {}
46
46
unsafe impl ReadableFromBytes for i64 { }
47
47
unsafe impl ReadableFromBytes for isize { }
48
48
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
+
49
75
/// A reference to an area in userspace memory, which can be either
50
76
/// read-only or read-write.
51
77
///
@@ -246,4 +272,11 @@ impl UserSlicePtrWriter {
246
272
self . 1 -= len;
247
273
Ok ( ( ) )
248
274
}
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
+ }
249
282
}
0 commit comments