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
use crate::HashMap;
use crate::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use cranelift_codegen::ir;
use lazy_static::lazy_static;

lazy_static! {
    static ref REGISTRY: RwLock<TrapRegistry> = RwLock::new(TrapRegistry::default());
}

/// The registry maintains descriptions of traps in currently allocated functions.
#[derive(Default)]
pub struct TrapRegistry {
    traps: HashMap<usize, TrapDescription>,
}

/// Description of a trap.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct TrapDescription {
    /// Location of the trap in source binary module.
    pub source_loc: ir::SourceLoc,
    /// Code of the trap.
    pub trap_code: ir::TrapCode,
}

/// RAII guard for deregistering traps
pub struct TrapRegistrationGuard(usize);

impl TrapRegistry {
    /// Registers a new trap.
    /// Returns a RAII guard that deregisters the trap when dropped.
    pub fn register_trap(
        &mut self,
        address: usize,
        source_loc: ir::SourceLoc,
        trap_code: ir::TrapCode,
    ) -> TrapRegistrationGuard {
        let entry = TrapDescription {
            source_loc,
            trap_code,
        };
        let previous_trap = self.traps.insert(address, entry);
        assert!(previous_trap.is_none());
        TrapRegistrationGuard(address)
    }

    fn deregister_trap(&mut self, address: usize) {
        assert!(self.traps.remove(&address).is_some());
    }

    /// Gets a trap description at given address.
    pub fn get_trap(&self, address: usize) -> Option<TrapDescription> {
        self.traps.get(&address).copied()
    }
}

impl Drop for TrapRegistrationGuard {
    fn drop(&mut self) {
        let mut registry = get_mut_trap_registry();
        registry.deregister_trap(self.0);
    }
}

/// Gets guarded writable reference to traps registry
pub fn get_mut_trap_registry() -> RwLockWriteGuard<'static, TrapRegistry> {
    REGISTRY.write().expect("trap registry lock got poisoned")
}

/// Gets guarded readable reference to traps registry
pub fn get_trap_registry() -> RwLockReadGuard<'static, TrapRegistry> {
    REGISTRY.read().expect("trap registry lock got poisoned")
}