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
//
// Copyright 2023, Colias Group, LLC
//
// SPDX-License-Identifier: MIT
//

use core::cell::UnsafeCell;

use crate::{InvocationContext, IpcBuffer};

mod token;

#[allow(unused_imports)]
use token::{Accessor, BorrowError, BorrowMutError, SyncToken, TokenCell, UnsyncToken};

// // //

#[repr(transparent)]
struct SyncUnsafeCell<T>(UnsafeCell<T>);

unsafe impl<T: Sync> Sync for SyncUnsafeCell<T> {}

#[repr(transparent)]
struct TokenCellWrapper<A>(TokenCell<TokenImpl, A>);

cfg_if::cfg_if! {
    if #[cfg(all(any(target_thread_local, feature = "tls"), not(feature = "non-thread-local-state")))] {
        type TokenImpl = UnsyncToken;

        const STATE_IS_THREAD_LOCAL: bool = true;

        macro_rules! maybe_add_thread_local_attr {
            { $item:item } => {
                #[thread_local]
                $item
            }
        }
    } else if #[cfg(not(feature = "thread-local-state"))] {
        cfg_if::cfg_if! {
            if #[cfg(feature = "single-threaded")] {
                unsafe impl<A> Sync for TokenCellWrapper<A> {}

                type TokenImpl = UnsyncToken;
            } else {
                type TokenImpl = SyncToken;
            }
        }

        const STATE_IS_THREAD_LOCAL: bool = false;

        macro_rules! maybe_add_thread_local_attr {
            { $item:item } => {
                $item
            }
        }
    } else {
        compile_error!(r#"invalid configuration"#);
    }
}

macro_rules! maybe_extern {
    { $ident:ident: $ty:ty = $init:expr; } => {
        cfg_if::cfg_if! {
            if #[cfg(feature = "extern-state")] {
                extern "C" {
                    maybe_add_thread_local_attr! {
                        static $ident: $ty;
                    }
                }
            } else {
                maybe_add_thread_local_attr! {
                    #[allow(non_upper_case_globals)]
                    #[cfg_attr(feature = "exposed-state", no_mangle)]
                    static $ident: $ty = $init;
                }
            }
        }
    }
}

// // //

maybe_extern! {
    __sel4_ipc_buffer: SyncUnsafeCell<Option<&'static mut IpcBuffer>> =
        SyncUnsafeCell(UnsafeCell::new(None));
}

struct IpcBufferAccessor;

impl Accessor<Option<&'static mut IpcBuffer>> for IpcBufferAccessor {
    #[allow(unused_unsafe)]
    fn with<F, U>(&self, f: F) -> U
    where
        F: FnOnce(&UnsafeCell<Option<&'static mut IpcBuffer>>) -> U,
    {
        f(unsafe { &__sel4_ipc_buffer.0 })
    }
}

maybe_add_thread_local_attr! {
    static IPC_BUFFER: TokenCellWrapper<IpcBufferAccessor> = unsafe {
        TokenCellWrapper(TokenCell::new(IpcBufferAccessor))
    };
}

/// Provides low-level access to this thread's IPC buffer.
///
/// This function does not modify kernel state. It only affects this crate's thread-local state.
///
/// Requires the `"state"` feature to be enabled.
pub fn try_with_ipc_buffer_slot<F, T>(f: F) -> T
where
    F: FnOnce(Result<&Option<&'static mut IpcBuffer>, BorrowError>) -> T,
{
    IPC_BUFFER.0.try_with(f)
}

/// Provides low-level mutable access to this thread's IPC buffer.
///
/// This function does not modify kernel state. It only affects this crate's thread-local state.
///
/// Requires the `"state"` feature to be enabled.
pub fn try_with_ipc_buffer_slot_mut<F, T>(f: F) -> T
where
    F: FnOnce(Result<&mut Option<&'static mut IpcBuffer>, BorrowMutError>) -> T,
{
    IPC_BUFFER.0.try_with_mut(f)
}

/// Provides access to this thread's IPC buffer.
///
/// Requires the `"state"` feature to be enabled.
pub fn with_ipc_buffer<F, T>(f: F) -> T
where
    F: FnOnce(&IpcBuffer) -> T,
{
    try_with_ipc_buffer_slot(|buf| f(buf.unwrap().as_ref().unwrap()))
}

/// Provides mutable access to this thread's IPC buffer.
///
/// Requires the `"state"` feature to be enabled.
pub fn with_ipc_buffer_mut<F, T>(f: F) -> T
where
    F: FnOnce(&mut IpcBuffer) -> T,
{
    try_with_ipc_buffer_slot_mut(|buf| f(buf.unwrap().as_mut().unwrap()))
}

/// Sets the IPC buffer that this crate will use for this thread.
///
/// This function does not modify kernel state. It only affects this crate's thread-local state.
///
/// Requires the `"state"` feature to be enabled.
pub fn set_ipc_buffer(ipc_buffer: &'static mut IpcBuffer) {
    try_with_ipc_buffer_slot_mut(|slot| {
        *slot.unwrap() = Some(ipc_buffer);
    })
}

/// Returns whether this crate's IPC buffer slot is thread-local.
///
/// Requires the `"state"` feature to be enabled.
pub const fn ipc_buffer_is_thread_local() -> bool {
    STATE_IS_THREAD_LOCAL
}

/// The strategy for discovering the current thread's IPC buffer which uses thread-local state.
///
/// This thread-local state can be modified using [`with_ipc_buffer`] and [`set_ipc_buffer`].
///
/// Requires the `"state"` feature to be enabled.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Hash)]
pub struct ImplicitInvocationContext;

impl ImplicitInvocationContext {
    pub const fn new() -> Self {
        Self
    }
}

impl InvocationContext for ImplicitInvocationContext {
    fn with_context<T>(&mut self, f: impl FnOnce(&mut IpcBuffer) -> T) -> T {
        with_ipc_buffer_mut(f)
    }
}