shadow_shim_helper_rs/
shim_shmem.rs

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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use linux_api::signal::{sigaction, siginfo_t, sigset_t, stack_t, Signal};
use shadow_shmem::allocator::{ShMemBlock, ShMemBlockSerialized};
use vasi::VirtualAddressSpaceIndependent;
use vasi_sync::scmutex::SelfContainedMutex;

use crate::option::FfiOption;
use crate::HostId;
use crate::{
    emulated_time::{AtomicEmulatedTime, EmulatedTime},
    rootedcell::{refcell::RootedRefCell, Root},
    simulation_time::SimulationTime,
};

// Validates that a type is safe to store in shared memory.
macro_rules! assert_shmem_safe {
    ($t:ty, $testfnname:ident) => {
        // Must be Sync, since it will be simultaneously available to multiple
        // threads (and processes).
        static_assertions::assert_impl_all!($t: Sync);

        // Must be VirtualAddressSpaceIndpendent, since it may be simultaneously
        // mapped into different virtual address spaces.
        static_assertions::assert_impl_all!($t: VirtualAddressSpaceIndependent);

        // Must have a stable layout.
        // This property is important if it's possible for code compiled in
        // different `rustc` invocations to access the shared memory. Theoretically,
        // with the current Shadow build layout, it *shouldn't* be needed, since this
        // code should be compiled only once before linking into both Shadow and the shim.
        // It would be easy to lose that property without noticing though, and end up with
        // very subtle memory bugs.
        //
        // We could also potentially dispense with this requirement for shared
        // memory only ever accessed via a dynamically linked library. Such a
        // library can only provided C abi public functions though.
        //
        // TODO: Consider instead implementing a trait like FFISafe, with a
        // derive-macro that validates that the type itself has an appropriate
        // `repr`, and that all of its fields are FFISafe. We could then
        // implement a trait `trait IsShmemSafe: Sync +
        // VirtualAddressSpaceIndpendent + FFISafe` instead of this macro
        // `assert_shmem_safe`, and enforce it in e.g. APIs that set up and
        // initialize shared memory.
        #[deny(improper_ctypes_definitions)]
        unsafe extern "C-unwind" fn $testfnname(_: $t) {}
    };
}

#[derive(VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct ManagerShmem {
    pub log_start_time_micros: i64,
}

#[derive(VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct HostShmem {
    pub host_id: HostId,

    pub protected: SelfContainedMutex<HostShmemProtected>,

    // Whether to model unblocked syscalls as taking non-zero time.
    // TODO: Move to a "ShimShmemGlobal" struct if we make one.
    pub model_unblocked_syscall_latency: bool,

    // Maximum accumulated CPU latency before updating clock.
    // TODO: Move to a "ShimShmemGlobal" struct if we make one, and if this
    // stays a global constant; Or down into the process if we make it a
    // per-process option.
    pub max_unapplied_cpu_latency: SimulationTime,

    // How much to move time forward for each unblocked syscall.
    // TODO: Move to a "ShimShmemGlobal" struct if we make one, and if this
    // stays a global constant; Or down into the process if we make it a
    // per-process option.
    pub unblocked_syscall_latency: SimulationTime,

    // How much to move time forward for each unblocked vdso "syscall".
    // TODO: Move to a "ShimShmemGlobal" struct if we make one, and if this
    // stays a global constant; Or down into the process if we make it a
    // per-process option.
    pub unblocked_vdso_latency: SimulationTime,

    // Native pid of the Shadow simulator process.
    pub shadow_pid: libc::pid_t,

    // Emulated CPU TSC clock rate, for rdtsc emulation.
    pub tsc_hz: u64,

    // Current simulation time.
    pub sim_time: AtomicEmulatedTime,

    pub shim_log_level: logger::LogLevel,

    pub manager_shmem: ShMemBlockSerialized,
}
assert_shmem_safe!(HostShmem, _hostshmem_test_fn);

impl HostShmem {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        host_id: HostId,
        model_unblocked_syscall_latency: bool,
        max_unapplied_cpu_latency: SimulationTime,
        unblocked_syscall_latency: SimulationTime,
        unblocked_vdso_latency: SimulationTime,
        shadow_pid: libc::pid_t,
        tsc_hz: u64,
        shim_log_level: ::logger::LogLevel,
        manager_shmem: &ShMemBlock<ManagerShmem>,
    ) -> Self {
        Self {
            host_id,
            protected: SelfContainedMutex::new(HostShmemProtected {
                host_id,
                root: Root::new(),
                unapplied_cpu_latency: SimulationTime::ZERO,
                max_runahead_time: EmulatedTime::MIN,
            }),
            model_unblocked_syscall_latency,
            max_unapplied_cpu_latency,
            unblocked_syscall_latency,
            unblocked_vdso_latency,
            shadow_pid,
            tsc_hz,
            sim_time: AtomicEmulatedTime::new(EmulatedTime::MIN),
            shim_log_level,
            manager_shmem: manager_shmem.serialize(),
        }
    }

    pub fn protected(&self) -> &SelfContainedMutex<HostShmemProtected> {
        &self.protected
    }
}

#[derive(VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct HostShmemProtected {
    pub host_id: HostId,

    pub root: Root,

    // Modeled CPU latency that hasn't been applied to the clock yet.
    pub unapplied_cpu_latency: SimulationTime,

    // Max simulation time to which sim_time may be incremented.  Moving time
    // beyond this value requires the current thread to be rescheduled.
    pub max_runahead_time: EmulatedTime,
}

#[derive(VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct ProcessShmem {
    host_id: HostId,

    /// Handle to shared memory for the Host
    pub host_shmem: ShMemBlockSerialized,
    pub strace_fd: FfiOption<libc::c_int>,

    pub protected: RootedRefCell<ProcessShmemProtected>,
}
assert_shmem_safe!(ProcessShmem, _test_processshmem_fn);

impl ProcessShmem {
    pub fn new(
        host_root: &Root,
        host_shmem: ShMemBlockSerialized,
        host_id: HostId,
        strace_fd: Option<libc::c_int>,
    ) -> Self {
        Self {
            host_id,
            host_shmem,
            strace_fd: strace_fd.into(),
            protected: RootedRefCell::new(
                host_root,
                ProcessShmemProtected {
                    host_id,
                    pending_signals: sigset_t::EMPTY,
                    pending_standard_siginfos: [siginfo_t::default();
                        Signal::STANDARD_MAX.as_i32() as usize],
                    signal_actions: [sigaction::default(); Signal::MAX.as_i32() as usize],
                },
            ),
        }
    }
}

#[derive(VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct ProcessShmemProtected {
    pub host_id: HostId,

    // Process-directed pending signals.
    pub pending_signals: sigset_t,

    // siginfo for each of the standard signals.
    // SAFETY: we ensure the internal pointers aren't dereferenced
    // outside of its original virtual address space.
    #[unsafe_assume_virtual_address_space_independent]
    pending_standard_siginfos: [siginfo_t; Signal::STANDARD_MAX.as_i32() as usize],

    // actions for both standard and realtime signals.
    // We currently support configuring handlers for realtime signals, but not
    // actually delivering them. This is to handle the case where handlers are
    // defensively installed, but not used in practice.
    // SAFETY: we ensure the internal pointers aren't dereferenced
    // outside of its original virtual address space.
    #[unsafe_assume_virtual_address_space_independent]
    signal_actions: [sigaction; Signal::MAX.as_i32() as usize],
}

// We have several arrays indexed by signal number - 1.
fn signal_idx(signal: Signal) -> usize {
    (i32::from(signal) - 1) as usize
}

impl ProcessShmemProtected {
    pub fn pending_standard_siginfo(&self, signal: Signal) -> Option<&siginfo_t> {
        if self.pending_signals.has(signal) {
            Some(&self.pending_standard_siginfos[signal_idx(signal)])
        } else {
            None
        }
    }

    pub fn set_pending_standard_siginfo(&mut self, signal: Signal, info: &siginfo_t) {
        assert!(self.pending_signals.has(signal));
        self.pending_standard_siginfos[signal_idx(signal)] = *info;
    }

    /// # Safety
    ///
    /// Only valid if pointers in `src` sigactions are valid in `self`'s address
    /// space (e.g. `src` is a parent that just forked this process).
    pub unsafe fn clone_signal_actions(&mut self, src: &Self) {
        self.signal_actions = src.signal_actions
    }

    /// # Safety
    ///
    /// Function pointers in `shd_kernel_sigaction::u` are valid only
    /// from corresponding managed process, and may be libc::SIG_DFL or
    /// libc::SIG_IGN.
    pub unsafe fn signal_action(&self, signal: Signal) -> &sigaction {
        &self.signal_actions[signal_idx(signal)]
    }

    /// # Safety
    ///
    /// Function pointers in `shd_kernel_sigaction::u` are valid only
    /// from corresponding managed process, and may be libc::SIG_DFL or
    /// libc::SIG_IGN.
    pub unsafe fn signal_action_mut(&mut self, signal: Signal) -> &mut sigaction {
        &mut self.signal_actions[signal_idx(signal)]
    }

    /// This drops all pending signals. Intended primarily for use with exec.
    pub fn clear_pending_signals(&mut self) {
        self.pending_signals = sigset_t::EMPTY;
    }

    pub fn take_pending_unblocked_signal(
        &mut self,
        thread: &ThreadShmemProtected,
    ) -> Option<(Signal, siginfo_t)> {
        let pending_unblocked_signals = self.pending_signals & !thread.blocked_signals;
        if pending_unblocked_signals.is_empty() {
            None
        } else {
            let signal = pending_unblocked_signals.lowest().unwrap();
            let info = *self.pending_standard_siginfo(signal).unwrap();
            self.pending_signals.del(signal);
            Some((signal, info))
        }
    }
}

#[derive(VirtualAddressSpaceIndependent)]
#[repr(C)]
pub struct ThreadShmem {
    pub host_id: HostId,
    pub tid: libc::pid_t,

    pub protected: RootedRefCell<ThreadShmemProtected>,
}
assert_shmem_safe!(ThreadShmem, _test_threadshmem_fn);

impl ThreadShmem {
    pub fn new(host: &HostShmemProtected, tid: libc::pid_t) -> Self {
        Self {
            host_id: host.host_id,
            tid,
            protected: RootedRefCell::new(
                &host.root,
                ThreadShmemProtected {
                    host_id: host.host_id,
                    pending_signals: sigset_t::EMPTY,
                    pending_standard_siginfos: [siginfo_t::default();
                        Signal::STANDARD_MAX.as_i32() as usize],
                    blocked_signals: sigset_t::EMPTY,
                    sigaltstack: StackWrapper(stack_t {
                        ss_sp: std::ptr::null_mut(),
                        ss_flags: libc::SS_DISABLE,
                        ss_size: 0,
                    }),
                },
            ),
        }
    }

    /// Create a copy of `Self`. We can't implement the `Clone` trait since we
    /// need the `root`.
    pub fn clone(&self, root: &Root) -> Self {
        Self {
            host_id: self.host_id,
            tid: self.tid,
            protected: RootedRefCell::new(root, *self.protected.borrow(root)),
        }
    }
}

#[derive(VirtualAddressSpaceIndependent, Copy, Clone)]
#[repr(C)]
pub struct ThreadShmemProtected {
    pub host_id: HostId,

    // Thread-directed pending signals.
    pub pending_signals: sigset_t,

    // siginfo for each of the 32 standard signals.
    // SAFETY: we ensure the internal pointers aren't dereferenced
    // outside of its original virtual address space.
    #[unsafe_assume_virtual_address_space_independent]
    pending_standard_siginfos: [siginfo_t; Signal::STANDARD_MAX.as_i32() as usize],

    // Signal mask, e.g. as set by `sigprocmask`.
    // We don't use sigset_t since glibc uses a much larger bitfield than
    // actually supported by the kernel.
    pub blocked_signals: sigset_t,

    // Configured alternate signal stack for this thread.
    sigaltstack: StackWrapper,
}

impl ThreadShmemProtected {
    pub fn pending_standard_siginfo(&self, signal: Signal) -> Option<&siginfo_t> {
        if self.pending_signals.has(signal) {
            Some(&self.pending_standard_siginfos[signal_idx(signal)])
        } else {
            None
        }
    }

    pub fn set_pending_standard_siginfo(&mut self, signal: Signal, info: &siginfo_t) {
        assert!(self.pending_signals.has(signal));
        self.pending_standard_siginfos[signal_idx(signal)] = *info;
    }

    /// # Safety
    ///
    /// `stack_t::ss_sp` must not be dereferenced except from corresponding
    /// managed thread.
    pub unsafe fn sigaltstack(&self) -> &stack_t {
        &self.sigaltstack.0
    }

    /// # Safety
    ///
    /// `stack_t::ss_sp` must not be dereferenced except from corresponding
    /// managed thread. Must be set to either std::ptr::null_mut, or a pointer valid
    /// in the managed thread.
    pub unsafe fn sigaltstack_mut(&mut self) -> &mut stack_t {
        &mut self.sigaltstack.0
    }

    pub fn take_pending_unblocked_signal(&mut self) -> Option<(Signal, siginfo_t)> {
        let pending_unblocked_signals = self.pending_signals & !self.blocked_signals;
        if pending_unblocked_signals.is_empty() {
            None
        } else {
            let signal = pending_unblocked_signals.lowest().unwrap();
            let info = *self.pending_standard_siginfo(signal).unwrap();
            self.pending_signals.del(signal);
            Some((signal, info))
        }
    }
}

#[derive(Copy, Clone)]
#[repr(transparent)]
struct StackWrapper(stack_t);

// SAFETY: We ensure the contained pointer isn't dereferenced
// except from the owning thread.
unsafe impl Send for StackWrapper {}

// SAFETY: We ensure the contained pointers isn't dereferenced
// except from the original virtual address space: in the shim.
unsafe impl VirtualAddressSpaceIndependent for StackWrapper {}

/// Take the next unblocked thread- *or* process-directed signal.
pub fn take_pending_unblocked_signal(
    lock: &HostShmemProtected,
    process: &ProcessShmem,
    thread: &ThreadShmem,
) -> Option<(Signal, siginfo_t)> {
    let mut thread_protected = thread.protected.borrow_mut(&lock.root);
    thread_protected
        .take_pending_unblocked_signal()
        .or_else(|| {
            let mut process_protected = process.protected.borrow_mut(&lock.root);
            process_protected.take_pending_unblocked_signal(&thread_protected)
        })
}

pub mod export {
    use std::sync::atomic::Ordering;

    use bytemuck::TransparentWrapper;
    use linux_api::signal::{linux_sigaction, linux_sigset_t, linux_stack_t};
    use vasi_sync::scmutex::SelfContainedMutexGuard;

    use super::*;
    use crate::{emulated_time::CEmulatedTime, simulation_time::CSimulationTime};

    // Legacy type names; keeping the more verbose names for the C API, since
    // they're not namespaced.
    pub type ShimShmemManager = ManagerShmem;
    pub type ShimShmemHost = HostShmem;
    pub type ShimShmemHostLock = HostShmemProtected;
    pub type ShimShmemProcess = ProcessShmem;
    pub type ShimShmemThread = ThreadShmem;

    /// # Safety
    ///
    /// `host` must be valid. The returned pointer must not be accessed from other threads.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmemhost_lock(
        host: *const ShimShmemHost,
    ) -> *mut ShimShmemHostLock {
        let host = unsafe { host.as_ref().unwrap() };
        let mut guard: SelfContainedMutexGuard<ShimShmemHostLock> = host.protected().lock();
        let lock: &mut ShimShmemHostLock = &mut guard;
        let lock = std::ptr::from_mut(lock);
        guard.disconnect();
        lock
    }

    /// # Safety
    ///
    /// `host` and `lock` must be valid.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmemhost_unlock(
        host: *const ShimShmemHost,
        lock: *mut *mut ShimShmemHostLock,
    ) {
        let host = unsafe { host.as_ref().unwrap() };
        let guard = SelfContainedMutexGuard::reconnect(&host.protected);
        assert_eq!(host.host_id, guard.host_id);

        let p_lock = unsafe { lock.as_mut().unwrap() };
        *p_lock = std::ptr::null_mut();
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getShadowPid(
        host_mem: *const ShimShmemHost,
    ) -> libc::pid_t {
        let host_mem = unsafe { host_mem.as_ref().unwrap() };
        host_mem.shadow_pid
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getTscHz(host_mem: *const ShimShmemHost) -> u64 {
        let host_mem = unsafe { host_mem.as_ref().unwrap() };
        host_mem.tsc_hz
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getLogLevel(
        host_mem: *const ShimShmemHost,
    ) -> ::logger::LogLevel {
        let host_mem = unsafe { host_mem.as_ref().unwrap() };
        host_mem.shim_log_level
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getEmulatedTime(
        host_mem: *const ShimShmemHost,
    ) -> CEmulatedTime {
        let host_mem = unsafe { host_mem.as_ref().unwrap() };
        EmulatedTime::to_c_emutime(Some(host_mem.sim_time.load(Ordering::Relaxed)))
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_setEmulatedTime(
        host_mem: *const ShimShmemHost,
        t: CEmulatedTime,
    ) {
        let host_mem = unsafe { host_mem.as_ref().unwrap() };
        host_mem
            .sim_time
            .store(EmulatedTime::from_c_emutime(t).unwrap(), Ordering::Relaxed);
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getMaxRunaheadTime(
        host_mem: *const ShimShmemHostLock,
    ) -> CEmulatedTime {
        let host_mem = unsafe { host_mem.as_ref().unwrap() };
        EmulatedTime::to_c_emutime(Some(host_mem.max_runahead_time))
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_setMaxRunaheadTime(
        host_mem: *mut ShimShmemHostLock,
        t: CEmulatedTime,
    ) {
        let host_mem = unsafe { host_mem.as_mut().unwrap() };
        host_mem.max_runahead_time = EmulatedTime::from_c_emutime(t).unwrap();
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getProcessStraceFd(
        process: *const ShimShmemProcess,
    ) -> libc::c_int {
        let process_mem = unsafe { process.as_ref().unwrap() };
        process_mem.strace_fd.unwrap_or(-1)
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getSignalAction(
        lock: *const ShimShmemHostLock,
        process: *const ShimShmemProcess,
        sig: i32,
    ) -> linux_sigaction {
        let process_mem = unsafe { process.as_ref().unwrap() };
        let lock = unsafe { lock.as_ref().unwrap() };
        let protected = process_mem.protected.borrow(&lock.root);
        unsafe { sigaction::peel(*protected.signal_action(Signal::try_from(sig).unwrap())) }
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_setSignalAction(
        lock: *const ShimShmemHostLock,
        process: *const ShimShmemProcess,
        sig: i32,
        action: *const linux_sigaction,
    ) {
        let process_mem = unsafe { process.as_ref().unwrap() };
        let lock = unsafe { lock.as_ref().unwrap() };
        let action = sigaction::wrap_ref(unsafe { action.as_ref().unwrap() });
        let mut protected = process_mem.protected.borrow_mut(&lock.root);
        unsafe { *protected.signal_action_mut(Signal::try_from(sig).unwrap()) = *action };
    }

    #[no_mangle]
    pub extern "C-unwind" fn shimshmemthread_size() -> usize {
        std::mem::size_of::<ThreadShmem>()
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getThreadId(
        thread: *const ShimShmemThread,
    ) -> libc::pid_t {
        let thread_mem = unsafe { thread.as_ref().unwrap() };
        thread_mem.tid
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getBlockedSignals(
        lock: *const ShimShmemHostLock,
        thread: *const ShimShmemThread,
    ) -> linux_sigset_t {
        let thread_mem = unsafe { thread.as_ref().unwrap() };
        let lock = unsafe { lock.as_ref().unwrap() };
        let protected = thread_mem.protected.borrow(&lock.root);
        sigset_t::peel(protected.blocked_signals)
    }

    /// Set the process's pending signal set.
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_setBlockedSignals(
        lock: *const ShimShmemHostLock,
        thread: *const ShimShmemThread,
        s: linux_sigset_t,
    ) {
        let thread_mem = unsafe { thread.as_ref().unwrap() };
        let lock = unsafe { lock.as_ref().unwrap() };
        let mut protected = thread_mem.protected.borrow_mut(&lock.root);
        protected.blocked_signals = sigset_t::wrap(s);
    }

    /// Get the signal stack as set by `sigaltstack(2)`.
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getSigAltStack(
        lock: *const ShimShmemHostLock,
        thread: *const ShimShmemThread,
    ) -> linux_stack_t {
        let thread_mem = unsafe { thread.as_ref().unwrap() };
        let lock = unsafe { lock.as_ref().unwrap() };
        let protected = thread_mem.protected.borrow(&lock.root);
        *unsafe { protected.sigaltstack() }
    }

    /// Set the signal stack as set by `sigaltstack(2)`.
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_setSigAltStack(
        lock: *const ShimShmemHostLock,
        thread: *const ShimShmemThread,
        stack: linux_stack_t,
    ) {
        let thread_mem = unsafe { thread.as_ref().unwrap() };
        let lock = unsafe { lock.as_ref().unwrap() };
        let mut protected = thread_mem.protected.borrow_mut(&lock.root);
        *unsafe { protected.sigaltstack_mut() } = stack;
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_incrementUnappliedCpuLatency(
        lock: *mut ShimShmemHostLock,
        dt: CSimulationTime,
    ) {
        let lock = unsafe { lock.as_mut().unwrap() };
        lock.unapplied_cpu_latency += SimulationTime::from_c_simtime(dt).unwrap();
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getUnappliedCpuLatency(
        lock: *const ShimShmemHostLock,
    ) -> CSimulationTime {
        let lock = unsafe { lock.as_ref().unwrap() };
        SimulationTime::to_c_simtime(Some(lock.unapplied_cpu_latency))
    }

    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_resetUnappliedCpuLatency(
        lock: *mut ShimShmemHostLock,
    ) {
        let lock = unsafe { lock.as_mut().unwrap() };
        lock.unapplied_cpu_latency = SimulationTime::ZERO;
    }

    /// Get whether to model latency of unblocked syscalls.
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getModelUnblockedSyscallLatency(
        host: *const ShimShmemHost,
    ) -> bool {
        let host = unsafe { host.as_ref().unwrap() };
        host.model_unblocked_syscall_latency
    }

    /// Get the configured maximum unblocked syscall latency to accumulate before
    /// yielding.
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_maxUnappliedCpuLatency(
        host: *const ShimShmemHost,
    ) -> CSimulationTime {
        let host = unsafe { host.as_ref().unwrap() };
        SimulationTime::to_c_simtime(Some(host.max_unapplied_cpu_latency))
    }

    /// Get the configured latency to emulate for each unblocked syscall.
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_unblockedSyscallLatency(
        host: *const ShimShmemHost,
    ) -> CSimulationTime {
        let host = unsafe { host.as_ref().unwrap() };
        SimulationTime::to_c_simtime(Some(host.unblocked_syscall_latency))
    }

    /// Get the configured latency to emulate for each unblocked vdso "syscall".
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_unblockedVdsoLatency(
        host: *const ShimShmemHost,
    ) -> CSimulationTime {
        let host = unsafe { host.as_ref().unwrap() };
        SimulationTime::to_c_simtime(Some(host.unblocked_vdso_latency))
    }

    /// Get the logging start time
    ///
    /// # Safety
    ///
    /// Pointer args must be safely dereferenceable.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn shimshmem_getLoggingStartTime(
        manager: *const ShimShmemManager,
    ) -> i64 {
        let manager = unsafe { manager.as_ref().unwrap() };
        manager.log_start_time_micros
    }
}