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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use crate::api::BackendAccess;
use crate::tracer::Tracer;
use crate::Gas;
use core::mem::MaybeUninit;
use polkavm_common::error::Trap;
use polkavm_common::program::Reg;
use polkavm_common::utils::{Access, AsUninitSliceMut};
use std::rc::{Rc, Weak};

pub(crate) struct CallerRaw {
    user_data: *mut core::ffi::c_void,
    access: *mut core::ffi::c_void,
    tracer: Option<Tracer>,
}

// SAFETY: Most of the methods of this struct are `unsafe` and the callers will uphold the invariants to ensure that this is safe.
unsafe impl Send for CallerRaw {}

// SAFETY: Most of the methods of this struct are `unsafe` and the callers will uphold the invariants to ensure that this is safe.
unsafe impl Sync for CallerRaw {}

impl CallerRaw {
    pub(crate) fn new(tracer: Option<Tracer>) -> Self {
        CallerRaw {
            user_data: core::ptr::null_mut(),
            access: core::ptr::null_mut(),
            tracer,
        }
    }

    unsafe fn data<T>(&self) -> &T {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { &*(self.user_data as *const T) }
    }

    unsafe fn data_mut<T>(&mut self) -> &mut T {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { &mut *self.user_data.cast::<T>() }
    }

    unsafe fn access(&self) -> &BackendAccess {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { &*(self.access.cast::<BackendAccess>().cast_const()) }
    }

    unsafe fn access_mut(&mut self) -> &mut BackendAccess {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { &mut *self.access.cast::<BackendAccess>() }
    }

    pub(crate) fn tracer(&mut self) -> Option<&mut Tracer> {
        self.tracer.as_mut()
    }

    unsafe fn get_reg(&self, reg: Reg) -> u32 {
        // SAFETY: The caller will make sure that the invariants hold.
        let value = unsafe { self.access() }.get_reg(reg);
        log::trace!("Getting register (during hostcall): {reg} = 0x{value:x}");
        value
    }

    unsafe fn set_reg(&mut self, reg: Reg, value: u32) {
        log::trace!("Setting register (during hostcall): {reg} = 0x{value:x}");

        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { self.access_mut() }.set_reg(reg, value);

        if let Some(ref mut tracer) = self.tracer() {
            tracer.on_set_reg_in_hostcall(reg, value);
        }
    }

    unsafe fn read_memory_into_slice<'slice, B>(&self, address: u32, buffer: &'slice mut B) -> Result<&'slice mut [u8], Trap>
    where
        B: ?Sized + AsUninitSliceMut,
    {
        // SAFETY: The caller will make sure that the invariants hold.
        let access = unsafe { self.access() };

        log::trace!(
            "Reading memory (during hostcall): 0x{:x}-0x{:x} ({} bytes)",
            address,
            (address as usize + buffer.as_uninit_slice_mut().len()) as u32,
            buffer.as_uninit_slice_mut().len()
        );
        access.read_memory_into_slice(address, buffer)
    }

    unsafe fn read_memory_into_vec(&self, address: u32, length: u32) -> Result<Vec<u8>, Trap> {
        log::trace!(
            "Reading memory (during hostcall): 0x{:x}-0x{:x} ({} bytes)",
            address,
            address.wrapping_add(length),
            length
        );

        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { self.access() }.read_memory_into_vec(address, length)
    }

    unsafe fn read_u32(&self, address: u32) -> Result<u32, Trap> {
        let mut buffer: MaybeUninit<[u8; 4]> = MaybeUninit::uninit();

        // SAFETY: The caller will make sure that the invariants hold.
        let slice = unsafe { self.read_memory_into_slice(address, &mut buffer) }?;
        let value = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]);
        Ok(value)
    }

    unsafe fn write_memory(&mut self, address: u32, data: &[u8]) -> Result<(), Trap> {
        log::trace!(
            "Writing memory (during hostcall): 0x{:x}-0x{:x} ({} bytes)",
            address,
            (address as usize + data.len()) as u32,
            data.len()
        );

        // SAFETY: The caller will make sure that the invariants hold.
        let result = unsafe { self.access_mut() }.write_memory(address, data);

        if let Some(ref mut tracer) = self.tracer() {
            tracer.on_memory_write_in_hostcall(address, data, result.is_ok())?;
        }

        result
    }

    unsafe fn sbrk(&mut self, size: u32) -> Option<u32> {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { self.access_mut() }.sbrk(size)
    }

    unsafe fn gas_remaining(&self) -> Option<Gas> {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { self.access() }.gas_remaining()
    }

    unsafe fn consume_gas(&mut self, gas: u64) {
        // SAFETY: The caller will make sure that the invariants hold.
        unsafe { self.access_mut() }.consume_gas(gas)
    }
}

/// A handle used to access the execution context.
pub struct Caller<'a, T> {
    raw: &'a mut CallerRaw,
    lifetime: *mut Option<Rc<()>>,
    _phantom: core::marker::PhantomData<&'a mut T>,
}

impl<'a, T> Caller<'a, T> {
    pub(crate) fn wrap<R>(
        user_data: &mut T,
        access: &'a mut BackendAccess<'_>,
        raw: &'a mut CallerRaw,
        callback: impl FnOnce(Self) -> R,
    ) -> R
    where
        T: 'a,
    {
        raw.user_data = (user_data as *mut T).cast::<core::ffi::c_void>();
        raw.access = (access as *mut BackendAccess).cast::<core::ffi::c_void>();

        let mut lifetime = None;
        let caller = Caller {
            raw,
            lifetime: &mut lifetime,
            _phantom: core::marker::PhantomData,
        };

        let result = callback(caller);

        core::mem::drop(lifetime);
        result
    }

    /// Creates a caller handle with dynamically checked borrow rules.
    pub fn into_ref(self) -> CallerRef<T> {
        let lifetime = Rc::new(());
        let lifetime_weak = Rc::downgrade(&lifetime);

        // SAFETY: This can only be called from inside of `Caller::wrap` so the pointer to `lifetime` is always valid.
        unsafe {
            *self.lifetime = Some(lifetime);
        }

        CallerRef {
            raw: self.raw,
            lifetime: lifetime_weak,
            _phantom: core::marker::PhantomData,
        }
    }

    pub fn split(self) -> (Caller<'a, ()>, &'a mut T) {
        let Caller { raw, lifetime, _phantom } = self;
        let dummy: *mut () = &mut () as *mut ();
        let dummy: *mut core::ffi::c_void = dummy.cast();
        let user_data: *mut core::ffi::c_void = core::mem::replace(&mut raw.user_data, dummy);
        let user_data: *mut T = user_data.cast();

        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        let user_data = unsafe { &mut *user_data };
        let caller = Caller {
            raw,
            lifetime,
            _phantom: core::marker::PhantomData,
        };

        (caller, user_data)
    }

    pub fn data(&self) -> &T {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.data() }
    }

    pub fn data_mut(&mut self) -> &mut T {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.data_mut() }
    }

    pub fn get_reg(&self, reg: Reg) -> u32 {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.get_reg(reg) }
    }

    pub fn set_reg(&mut self, reg: Reg, value: u32) {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.set_reg(reg, value) }
    }

    pub fn read_memory_into_slice<'slice, B>(&self, address: u32, buffer: &'slice mut B) -> Result<&'slice mut [u8], Trap>
    where
        B: ?Sized + AsUninitSliceMut,
    {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.read_memory_into_slice(address, buffer) }
    }

    pub fn read_memory_into_vec(&self, address: u32, length: u32) -> Result<Vec<u8>, Trap> {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.read_memory_into_vec(address, length) }
    }

    pub fn read_u32(&self, address: u32) -> Result<u32, Trap> {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.read_u32(address) }
    }

    pub fn write_memory(&mut self, address: u32, data: &[u8]) -> Result<(), Trap> {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.write_memory(address, data) }
    }

    pub fn sbrk(&mut self, size: u32) -> Option<u32> {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.sbrk(size) }
    }

    pub fn gas_remaining(&self) -> Option<Gas> {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.gas_remaining() }
    }

    pub fn consume_gas(&mut self, gas: u64) {
        // SAFETY: This can only be called from inside of `Caller::wrap` so this is always valid.
        unsafe { self.raw.consume_gas(gas) }
    }
}

/// A handle used to access the execution context, with erased lifetimes for convenience.
///
/// Can only be used from within the handler to which the original [`Caller`] was passed.
/// Will panic if used incorrectly.
pub struct CallerRef<T> {
    raw: *mut CallerRaw,
    lifetime: Weak<()>,
    _phantom: core::marker::PhantomData<T>,
}

impl<T> CallerRef<T> {
    fn check_lifetime_or_panic(&self) {
        assert!(self.lifetime.strong_count() > 0, "CallerRef accessed outside of a hostcall handler");
    }

    pub fn data(&self) -> &T {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).data() }
    }

    pub fn data_mut(&mut self) -> &mut T {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).data_mut() }
    }

    pub fn get_reg(&self, reg: Reg) -> u32 {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).get_reg(reg) }
    }

    pub fn set_reg(&mut self, reg: Reg, value: u32) {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).set_reg(reg, value) }
    }

    pub fn read_memory_into_slice<'slice, B>(&self, address: u32, buffer: &'slice mut B) -> Result<&'slice mut [u8], Trap>
    where
        B: ?Sized + AsUninitSliceMut,
    {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).read_memory_into_slice(address, buffer) }
    }

    pub fn read_memory_into_vec(&self, address: u32, length: u32) -> Result<Vec<u8>, Trap> {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).read_memory_into_vec(address, length) }
    }

    pub fn read_u32(&self, address: u32) -> Result<u32, Trap> {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).read_u32(address) }
    }

    pub fn write_memory(&mut self, address: u32, data: &[u8]) -> Result<(), Trap> {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).write_memory(address, data) }
    }

    pub fn gas_remaining(&self) -> Option<Gas> {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).gas_remaining() }
    }

    pub fn consume_gas(&mut self, gas: u64) {
        self.check_lifetime_or_panic();

        // SAFETY: We've made sure the lifetime is valid.
        unsafe { (*self.raw).consume_gas(gas) }
    }
}

// Source: https://users.rust-lang.org/t/a-macro-to-assert-that-a-type-does-not-implement-trait-bounds/31179
macro_rules! assert_not_impl {
    ($x:ty, $($t:path),+ $(,)*) => {
        const _: fn() -> () = || {
            struct Check<T: ?Sized>(T);
            trait AmbiguousIfImpl<A> { fn some_item() { } }

            impl<T: ?Sized> AmbiguousIfImpl<()> for Check<T> { }
            impl<T: ?Sized $(+ $t)*> AmbiguousIfImpl<u8> for Check<T> { }

            <Check::<$x> as AmbiguousIfImpl<_>>::some_item()
        };
    };
}

assert_not_impl!(CallerRef<()>, Send);
assert_not_impl!(CallerRef<()>, Sync);
assert_not_impl!(Caller<'static, ()>, Send);
assert_not_impl!(Caller<'static, ()>, Sync);