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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
//! Type-safe hunks
use core::{
    fmt,
    marker::PhantomData,
    mem,
    ops::Deref,
    ptr::{slice_from_raw_parts, slice_from_raw_parts_mut},
};

use crate::{
    kernel::{self, cfg, hunk, raw, raw_cfg, Cfg, StartupHook},
    utils::{Init, Zeroable},
};

/// The priority of the [startup hooks] used to initialize [typed hunks]. It has
/// a negative value so that startup hooks with non-negative priorities (which
/// can be created without `unsafe` blocks) will never see an uninitialized
/// value in a typed hunk.
///
/// [startup hooks]: crate::kernel::StartupHook
/// [typed hunks]: Hunk
pub const INIT_HOOK_PRIORITY: i32 = -0x7000_0000;

/// Represents a single typed hunk in a system.
///
/// Hunks are nothing more than static variables defined in a kernel
/// configuration. They come in handy when you are designing a component that
/// can be instantiated by a kernel configuration and wanting each instance to
/// have its own separate state data.
///
/// This type is implemented on top of [`r3::kernel::Hunk`], the untyped
/// hunk type.
///
/// [`r3::kernel::Hunk`]: crate::kernel::Hunk
#[doc = include_str!("./common.md")]
pub struct Hunk<System, T: ?Sized> {
    /// The offset of the hunk. `System::HUNK_ATTR.hunk_pool_ptr()` must be
    /// added before dereferencing.
    offset: *const T,
    _phantom: PhantomData<System>,
}

unsafe impl<System, T: ?Sized + Send> Send for Hunk<System, T> {}
unsafe impl<System, T: ?Sized + Sync> Sync for Hunk<System, T> {}

impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized> Hunk<System, T> {
    /// Construct a `HunkDefiner` to define a hunk in [a configuration
    /// function](crate#static-configuration).
    pub const fn define() -> HunkDefiner<System, T, DefaultInitTag> {
        HunkDefiner {
            _phantom: PhantomData,
            len: 1,
            align: 1,
        }
    }
}

/// As a generic parameter of [`HunkDefiner`], indicates that the [hunk]
/// should be initialized with [`Init`].
///
/// [`Init`]: crate::utils::Init
/// [hunk]: crate::kernel::Hunk
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct DefaultInitTag;

/// As a generic parameter of [`HunkDefiner`], indicates that the [hunk]
/// should be zero-initialized.
///
/// [hunk]: crate::kernel::Hunk
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct ZeroInitTag;

/// Implemented on [`DefaultInitTag`] and [`ZeroInitTag`] when `T` can be
/// initialized in this way.
pub trait HunkIniter<T> {
    /// A flag indicating whether [`Self::init`] should be called for
    /// initialization.
    const NEEDS_INIT: bool;

    /// Initialize the specified memory region.
    fn init(dest: &mut mem::MaybeUninit<T>);
}

impl<T: Init> HunkIniter<T> for DefaultInitTag {
    const NEEDS_INIT: bool = true;
    fn init(dest: &mut mem::MaybeUninit<T>) {
        *dest = mem::MaybeUninit::new(T::INIT);
    }
}

impl<T> HunkIniter<T> for ZeroInitTag {
    const NEEDS_INIT: bool = false;
    fn init(_: &mut mem::MaybeUninit<T>) {
        // Do nothing - a hunk pool is zero-initialized by default
        // [ref:hunk_pool_is_zeroed]
    }
}

/// The definer (static builder) for [`Hunk`].
///
/// `InitTag` is either [`DefaultInitTag`] or [`ZeroInitTag`].
#[must_use = "must call `finish()` to complete registration"]
pub struct HunkDefiner<System, T: ?Sized, InitTag> {
    _phantom: PhantomData<(System, InitTag, T)>,
    len: usize,
    align: usize,
}

impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized, InitTag>
    HunkDefiner<System, T, InitTag>
{
    /// Specify the element count. Defaults to `1`. Must be `1` for a non-array
    /// hunk.
    pub const fn len(self, len: usize) -> Self {
        Self { len, ..self }
    }

    /// Specify the minimum alignment. Defaults to `1`.
    pub const fn align(self, align: usize) -> Self {
        Self { align, ..self }
    }

    /// Zero-initialize the hunk.
    pub const fn zeroed(self) -> HunkDefiner<System, T, ZeroInitTag>
    where
        T: Zeroable,
    {
        // Safety: `T: Zeroable`, so it's zero-initializable
        unsafe { self.zeroed_unchecked() }
    }

    /// Zero-initialize the hunk even if it might be unsafe.
    ///
    /// # Safety
    ///
    /// If zero initialization is not a valid bit pattern for `T`, accessing the
    /// hunk's contents may result in an undefined behavior.
    pub const unsafe fn zeroed_unchecked(self) -> HunkDefiner<System, T, ZeroInitTag> {
        HunkDefiner {
            _phantom: PhantomData,
            len: self.len,
            align: self.align,
        }
    }
}

impl<System: raw::KernelBase + cfg::KernelStatic, T, InitTag: HunkIniter<T>>
    HunkDefiner<System, T, InitTag>
{
    /// Complete the definition of a hunk, returning a reference to the hunk.
    pub const fn finish<C: ~const raw_cfg::CfgBase<System = System>>(
        self,
        cfg: &mut Cfg<C>,
    ) -> Hunk<System, T> {
        let untyped_hunk = kernel::Hunk::<System>::define()
            .len(mem::size_of::<T>())
            .align(mem::align_of::<T>().max(self.align))
            .finish(cfg);

        assert!(self.len == 1, "Non-array hunk must have `len` of `1`");

        let start = untyped_hunk.offset();

        // Insert an initializer
        if InitTag::NEEDS_INIT {
            unsafe {
                StartupHook::define()
                    .priority(INIT_HOOK_PRIORITY)
                    .start((start, |start| {
                        let untyped_hunk = kernel::Hunk::<System>::from_offset(start).as_ptr();
                        // Safety: The destination is large enough to contain `T`
                        InitTag::init(&mut *untyped_hunk.cast());
                    }))
                    .unchecked()
                    .finish(cfg);
            }
        }

        Hunk {
            offset: start as _,
            _phantom: PhantomData,
        }
    }
}

impl<System: raw::KernelBase + cfg::KernelStatic, T, InitTag: HunkIniter<T>>
    HunkDefiner<System, [T], InitTag>
{
    /// Complete the definition of a hunk, returning a reference to the hunk.
    pub const fn finish<C: ~const raw_cfg::CfgBase<System = System>>(
        self,
        cfg: &mut Cfg<C>,
    ) -> Hunk<System, [T]> {
        assert!(self.align.is_power_of_two(), "`align` is not power of two");

        let untyped_hunk = kernel::Hunk::<System>::define()
            .len(mem::size_of::<T>() * self.len)
            .align(mem::align_of::<T>().max(self.align))
            .finish(cfg);

        let start = untyped_hunk.offset();

        // Insert an initializer
        if InitTag::NEEDS_INIT {
            // TODO: There is no way to pass a length into the initializer
            todo!();
        }

        Hunk {
            offset: slice_from_raw_parts_mut(start as _, self.len),
            _phantom: PhantomData,
        }
    }
}

impl<System: raw::KernelBase + cfg::KernelStatic, T> Init for Hunk<System, [T]> {
    // Safety: This is safe because it points to nothing
    #[allow(clippy::invalid_null_ptr_usage)]
    const INIT: Self = Self {
        offset: slice_from_raw_parts_mut(core::ptr::null_mut(), 0),
        _phantom: PhantomData,
    };
}

impl<System: raw::KernelBase + cfg::KernelStatic, T: fmt::Debug + ?Sized> fmt::Debug
    for Hunk<System, T>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Hunk")
            .field(&Self::as_ptr(*self))
            .field(&&**self)
            .finish()
    }
}

impl<System, T: ?Sized> Clone for Hunk<System, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<System, T: ?Sized> Copy for Hunk<System, T> {}

impl<System, T: ?Sized> Hunk<System, T> {
    /// Reinterpret the hunk as another type.
    ///
    /// # Safety
    ///
    ///  - Similarly to [`core::mem::transmute`], this is **incredibly** unsafe.
    ///  - The byte offset must be valid for the destination type.
    ///
    pub const unsafe fn transmute<U>(self) -> Hunk<System, U> {
        Hunk {
            offset: self.offset.cast(),
            _phantom: PhantomData,
        }
    }

    /// Calculate the offset from the hunk.
    ///
    /// # Safety
    ///
    ///  - The resulting hunk may point to memory that the caller is not
    ///    supposed to access.
    ///
    pub const unsafe fn wrapping_offset(self, count: isize) -> Self
    where
        T: Sized,
    {
        Hunk {
            offset: self.offset.wrapping_offset(count),
            _phantom: PhantomData,
        }
    }
}

impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized> Hunk<System, T> {
    /// Get the untyped hunk.
    #[inline]
    pub fn untyped_hunk(this: Self) -> kernel::Hunk<System> {
        hunk::Hunk::from_offset(this.offset as *const u8 as usize)
    }

    // The following methods are not `const fn` on account of `const`s being
    // unable to refer to `static`s [ref:const_static_item_ref]

    /// Get a raw pointer to the hunk's contents.
    #[inline]
    pub fn as_ptr(this: Self) -> *const T {
        Self::untyped_hunk(this)
            .as_ptr()
            .cast_const()
            .with_metadata_of(this.offset)
    }

    /// Get a raw pointer to the raw bytes of the hunk.
    #[inline]
    pub fn as_bytes_ptr(this: Self) -> *const [u8] {
        slice_from_raw_parts(Self::untyped_hunk(this).as_ptr(), mem::size_of_val(&*this))
    }

    /// Get a reference to the hunk's contents.
    #[inline]
    #[allow(clippy::should_implement_trait)]
    pub fn as_ref<'a>(this: Self) -> &'a T
    where
        T: 'a,
    {
        unsafe { &*Self::as_ptr(this) }
    }

    /// Get a reference to the raw bytes of the hunk.
    ///
    /// # Safety
    ///
    /// The result might include uninitialized bytes and/or interior mutability,
    /// so it might be unsafe to access.
    #[inline]
    pub unsafe fn as_bytes(this: Self) -> &'static [u8] {
        // Safety: The caller is responsible for making sure interpreting the
        // contents as `[u8]` is safe
        unsafe { &*Self::as_bytes_ptr(this) }
    }
}

impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized> AsRef<T> for Hunk<System, T> {
    #[inline]
    fn as_ref(&self) -> &T {
        unsafe { &*Self::as_ptr(*self) }
    }
}

impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized> Deref for Hunk<System, T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

// Safety: `Hunk::deref` provides a stable address
unsafe impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized> stable_deref_trait::StableDeref
    for Hunk<System, T>
{
}

// Safety: `Hunk::clone` preserves the address
unsafe impl<System: raw::KernelBase + cfg::KernelStatic, T: ?Sized>
    stable_deref_trait::CloneStableDeref for Hunk<System, T>
{
}