Skip to content
This repository was archived by the owner on Jul 2, 2021. It is now read-only.

Commit 69f787a

Browse files
Introduce a Word trait for the init routines
1 parent 00f103f commit 69f787a

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

src/lib.rs

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,36 @@ mod test;
5555

5656
use core::{mem, ptr};
5757

58+
mod sealed {
59+
pub trait Sealed {}
60+
}
61+
62+
/// Trait for machine word types.
63+
///
64+
/// This trait is implemented by unsigned integers representing common machine
65+
/// word sizes. It can not be implemented by the user.
66+
///
67+
/// Types implementing this trait can be used by the [`init_data`] and
68+
/// [`zero_bss`] functions. For that to be sound, all bit patterns need to be
69+
/// valid for the type, the type must implement `Copy`, and the type must not
70+
/// be zero-sized.
71+
///
72+
/// [`init_data`]: fn.init_data.html
73+
/// [`zero_bss`]: fn.zero_bss.html
74+
pub unsafe trait Word: sealed::Sealed + Copy {}
75+
76+
impl sealed::Sealed for u8 {}
77+
impl sealed::Sealed for u16 {}
78+
impl sealed::Sealed for u32 {}
79+
impl sealed::Sealed for u64 {}
80+
impl sealed::Sealed for u128 {}
81+
82+
unsafe impl Word for u8 {}
83+
unsafe impl Word for u16 {}
84+
unsafe impl Word for u32 {}
85+
unsafe impl Word for u64 {}
86+
unsafe impl Word for u128 {}
87+
5888
/// Initializes the `.data` section.
5989
///
6090
/// # Arguments
@@ -67,18 +97,17 @@ use core::{mem, ptr};
6797
///
6898
/// # Safety
6999
///
70-
/// - Must be called exactly once
71-
/// - `mem::size_of::<T>()` must be non-zero
72-
/// - `edata >= sdata`
100+
/// - Must be called exactly once, before the application has started.
101+
/// - `edata >= sdata`.
73102
/// - The `sdata -> edata` region must not overlap with the `sidata -> ...`
74-
/// region
103+
/// region.
75104
/// - `sdata`, `edata` and `sidata` must be `T` aligned.
76105
pub unsafe fn init_data<T>(
77106
mut sdata: *mut T,
78107
edata: *mut T,
79108
mut sidata: *const T,
80109
) where
81-
T: Copy,
110+
T: Word,
82111
{
83112
while sdata < edata {
84113
ptr::write(sdata, ptr::read(sidata));
@@ -98,13 +127,12 @@ pub unsafe fn init_data<T>(
98127
///
99128
/// # Safety
100129
///
101-
/// - Must be called exactly once
102-
/// - `mem::size_of::<T>()` must be non-zero
103-
/// - `ebss >= sbss`
130+
/// - Must be called exactly once, before the application has started.
131+
/// - `ebss >= sbss`.
104132
/// - `sbss` and `ebss` must be `T` aligned.
105133
pub unsafe fn zero_bss<T>(mut sbss: *mut T, ebss: *mut T)
106134
where
107-
T: Copy,
135+
T: Word,
108136
{
109137
while sbss < ebss {
110138
// NOTE(volatile) to prevent this from being transformed into `memclr`

0 commit comments

Comments
 (0)