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
//! Shadow stack implementation for rooting in GCs
//!
//!
//! # Description
//! Unlike other algorithms to take care of rooted objects like use reference counting to take count of instances
//! on stack, this algorithm maintains a singly linked list of stack roots. This so-called "shadow stack" mirrors the
//! machine stack. Maintaining this data is much faster and memory-efficent than using reference-counted stack roots,
//! it does not require heap allocation, and does not rely on compiler optimizations.
#![no_std]

pub use mopa;
pub use paste;

/// Instatiate shadow stack type that can work with your GC API.
///
/// # Paramters
/// - `$name`: Shadow stack type name itself.
/// - `$traceable`: Your GC traceable trait that is implemented for all types that can be traced.
/// - `$rootable`: New trait name that should be implemented for rooted values.
/// - `$rooted`: Type of rooted value.
/// - `$handle`: Type of reference to rooted value. This creates `$handle` and `$handle Mut` types.
/// - `$letroot`: Name that is given to macro that will instantiate rooted values.
///
#[macro_export]
macro_rules! gc_shadowstack {
    ($name: ident,$traceable: path,$rootable: ident,$rooted: ident,$handle: ident,$letroot: ident) => {

        $crate::paste::paste!(

            /// Shadow stack implementation. Internally this is singly-linked list of on stack rooted values.
            pub struct $name {
                #[doc(hidden)]
                pub head: core::cell::Cell<*mut [<Raw $name Entry>]>,
            }


            impl $name {
                /// Create new shadow stack instance.
                pub fn new() -> Self {
                    Self {
                        head: core::cell::Cell::new(core::ptr::null_mut())
                    }
                }
                /// Walk all rooted values in this shadow stack.
                ///
                /// # Safety
                /// TODO: I don't really know if this method should be safe or unsafe.
                ///
                pub unsafe fn walk(&self,mut visitor: impl FnMut(&mut dyn $rootable)) {
                    let mut head = *self.head.as_ptr();
                    while !head.is_null() {
                        let next = (*head).prev;
                        visitor((*head).get_dyn());
                        head = next;
                    }
                }
            }


        );

        $crate::paste::paste!{
            /// Raw entry in GC shadow stack. Internal fields is not exposed in public API in any ways.
            ///
            ///
            /// This type internally stores shadow stack pointeter,previous pointer from the list and vtable
            /// that is used to construct `dyn` trait.
            ///
            #[repr(C)]
            pub struct [<Raw $name Entry>] {
                /// Shadowstack itself
                stack: *mut $name,
                /// Previous rooted entry
                prev: *mut [<Raw $name Entry>],
                /// Pointer to vtable that is a `Trace` of rooted variable
                vtable: usize,
                /// Value is located right after vtable pointer, to access it we can construct trait object.
                data_start: [u8; 0],
            }
        }
        /// Trait that should be implemented for all types that could be rooted.
        /// In simple cases `impl<T: Traceable> Rootable for T {}` is enough.
        pub trait $rootable: $traceable {}
        $crate::paste::paste!(
            impl [<Raw $name Entry>] {
                /// Obtain mutable reference to rooted value.
                ///
                /// # Safety
                /// This method is `&self` but returns `&mut dyn` which is *very* unsafey. If moving GC uses shadow stack
                /// it should be ***very*** accurate when moving objects around.
                pub unsafe fn get_dyn(&self) -> &mut dyn $rootable {
                    core::mem::transmute($crate::mopa::TraitObject {
                        vtable: self.vtable as _,
                        data: self.data_start.as_ptr() as *mut (),
                    })
                }
            }

            /// Almost the same as raw entry of shadow stack except this one gives access to value.
            /// This type is not exposed in public API and used only internally.
            #[repr(C)]
            pub struct [<$name Internal>]<'a,T: $rootable> {
                pub stack :&'a $name,
                pub prev: *mut [<Raw $name Entry>],
                pub vtable: usize,
                pub value: T
            }

           impl<'a, T:$rootable> [<$name Internal>]<'a, T> {
                /// Constructs internal shadow stack value. Must not be used outside of `$letroot!` macro.
                #[inline]
                pub unsafe fn construct(
                    stack: &'a ShadowStack,
                    prev: *mut [<Raw $name Entry>],
                    vtable: usize,
                    value: T,
                ) -> Self {
                    Self {
                        stack,
                        prev,
                        vtable,
                        value,
                    }
                }
            }

            impl<T: $rootable> Drop for [<$name Internal>]<'_,T> {
                /// Drop current shadow stack entry and update shadow stack state.
                fn drop(&mut self) {
                    (*self.stack).head.set(self.prev);
                }
            }

            /// Rooted value on stack. This is non-copyable type that is used to hold GC thing on stack.
            pub struct $rooted<'a, 'b, T: $rootable> {
                #[doc(hidden)]
                pinned: core::pin::Pin<&'a mut [<$name Internal>]<'b, T>>,
            }

            impl<'a, 'b, T: $rootable> $rooted<'a, 'b, T> {
                /// Create rooted value from pinned reference. Note that this function must be used only
                /// inside `$letroot` macro.
                pub unsafe fn construct(pin: core::pin::Pin<&'a mut [< $name Internal>]<'b, T>>) -> Self {
                    Self { pinned: pin }
                }
                pub unsafe fn get_internal(&self) -> &[<$name Internal>]<T> {
                    core::mem::transmute_copy::<_, _>(&self.pinned)
                }
                pub unsafe fn get_internal_mut(&mut self) -> &mut  &[<$name Internal>]<T> {
                    core::mem::transmute_copy::<_, _>(&self.pinned)
                }

                pub fn mut_handle(&mut self) -> [<$handle Mut>]<'_, T> {
                    HandleMut { value: &mut **self }
                }

                pub fn handle(&self) -> $handle<'_, T> {
                    Handle { value: &**self }
                }
            }

            impl<'a, T: $rootable> core::ops::Deref for $rooted<'a, '_, T> {
                type Target = T;
                fn deref(&self) -> &Self::Target {
                    &self.pinned.value
                }
            }

            impl<'a, T: $rootable> core::ops::DerefMut for $rooted<'a, '_, T> {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    unsafe {
                        &mut core::mem::transmute_copy::<_, &mut [<$name Internal>]<T>>(&mut self.pinned).value
                    }
                }
            }

            /// Reference to rooted value.
            pub struct $handle<'a, T: $rootable> {
                value: &'a T,
            }
            /// Mutable reference to rooted value.
            pub struct [<$handle Mut>]<'a, T: $rootable> {
                value: &'a mut T,
            }

            impl<'a, T: $rootable> [<$handle Mut>]<'a, T> {
                pub fn set(&mut self, value: T) -> T {
                    core::mem::replace(self.value, value)
                }
            }
            impl<T: $rootable> core::ops::Deref for $handle<'_, T> {
                type Target = T;
                fn deref(&self) -> &Self::Target {
                    self.value
                }
            }

            impl<T: $rootable> core::ops::Deref for [<$handle Mut>]<'_, T> {
                type Target = T;
                fn deref(&self) -> &Self::Target {
                    self.value
                }
            }
            impl<T: $rootable> core::ops::DerefMut for [<$handle Mut>]<'_, T> {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    self.value
                }
            }


            /// Create rooted value and push it to provided shadowstack instance.
            ///
            ///
            /// ***NOTE***: This macro does not heap allocate internally. It uses some unsafe tricks to
            /// allocate value on stack and push stack reference to shadowstack. Returned rooted value internally
            /// is `Pin<&mut T>`.
            ///
            #[macro_export]
            macro_rules! $letroot {
                ($var_name: ident: $t: ty  = $stack: expr,$value: expr) => {
                    let stack: &$name = &$stack;
                    let value = $value;
                    let mut $var_name = unsafe {
                        [<$name Internal>]::<$t>::construct(
                            stack,
                            stack.head.get(),
                            core::mem::transmute::<_, $crate::mopa::TraitObject>(&value as &dyn $rootable)
                                .vtable as usize,
                            value,
                        )
                    };

                    stack.head.set(unsafe { core::mem::transmute(&mut $var_name) });
                    #[allow(unused_mut)]
                    let mut $var_name =
                        unsafe { $rooted::construct(std::pin::Pin::new(&mut $var_name)) };
                };

                ($var_name : ident = $stack: expr,$value: expr) => {
                    let stack: &$name = &$stack;
                    let value = $value;
                    let mut $var_name = unsafe {
                       [<$name Internal>]::<_>::construct(
                            stack,
                            stack.head.get(),
                            core::mem::transmute::<_, $crate::mopa::TraitObject>(&value as &dyn $rootable)
                                .vtable as usize,
                            value,
                        )
                    };

                    stack.head.set(unsafe { core::mem::transmute(&mut $var_name) });
                    #[allow(unused_mut)]
                    let mut $var_name =
                        unsafe { $rooted::construct(core::pin::Pin::new(&mut $var_name)) };
                };
            }
        );
    };
}

#[cfg(doc)]
pub mod dummy {
    //! Dummy module that generates shadow stack type to see documentation of all APIs provided.
    pub trait Traceable {}
    gc_shadowstack!(
        ShadowStack,
        Traceable,
        Rootable,
        Rooted,
        Handle,
        dummy_letroot
    );
}