Skip to main content

foundry_evm_coverage/
inspector.rs

1use crate::{CallData, HitMap, HitMaps};
2use alloy_primitives::B256;
3use evm2::{
4    EvmTypesHost, Inspector,
5    interpreter::{Interpreter, Message, MessageResult},
6};
7use std::ptr::NonNull;
8
9/// Inspector implementation for collecting coverage information.
10#[derive(Clone, Debug)]
11pub struct LineCoverageCollector {
12    // NOTE: `current_map` is always a valid reference into `maps`.
13    // It is accessed only through `get_or_insert_map` which guarantees that it's valid.
14    // Both of these fields are unsafe to access directly outside of `*insert_map`.
15    current_map: NonNull<HitMap>,
16    current_hash: B256,
17
18    maps: HitMaps,
19}
20
21// SAFETY: See comments on `current_map`.
22unsafe impl Send for LineCoverageCollector {}
23unsafe impl Sync for LineCoverageCollector {}
24
25impl Default for LineCoverageCollector {
26    fn default() -> Self {
27        Self {
28            current_map: NonNull::dangling(),
29            current_hash: B256::ZERO,
30            maps: Default::default(),
31        }
32    }
33}
34
35impl<T: EvmTypesHost> Inspector<T> for LineCoverageCollector {
36    fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, T>) {
37        let message = interp.message();
38        let call = (!message.kind.is_create())
39            .then(|| (CallData::new(interp.input()), !message.value.is_zero()));
40        let map = self.get_or_insert_map(interp);
41        if let Some((call, with_value)) = call {
42            map.call(call, with_value);
43        }
44    }
45
46    fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
47        let pc = interp.pc();
48        self.get_or_insert_map(interp).record(pc);
49    }
50
51    fn create_end(
52        &mut self,
53        _interp: &mut Interpreter<'_, '_, T>,
54        message: &Message<T>,
55        result: &mut MessageResult<T>,
56    ) {
57        if result.stop.is_success()
58            && let Some(map) = self.maps.get_mut(&message.code.hash_slow())
59        {
60            map.creation();
61        }
62    }
63}
64
65impl LineCoverageCollector {
66    /// Finish collecting coverage information and return the [`HitMaps`].
67    pub fn finish(mut self) -> HitMaps {
68        self.maps.values_mut().for_each(HitMap::flush);
69        self.maps
70    }
71
72    /// Gets the hit map for the current contract, or inserts a new one if it doesn't exist.
73    ///
74    /// The map is stored in `current_map` and returned as a mutable reference.
75    /// See comments on `current_map` for more details.
76    #[inline]
77    fn get_or_insert_map<T: EvmTypesHost>(
78        &mut self,
79        interp: &Interpreter<'_, '_, T>,
80    ) -> &mut HitMap {
81        let hash = interp.original_bytecode_hash();
82        if self.current_hash != hash {
83            self.insert_map(hash, interp);
84        }
85        // SAFETY: See comments on `current_map`.
86        unsafe { self.current_map.as_mut() }
87    }
88
89    #[cold]
90    #[inline(never)]
91    fn insert_map<T: EvmTypesHost>(&mut self, hash: B256, interp: &Interpreter<'_, '_, T>) {
92        self.current_hash = hash;
93        // Converts the mutable reference to a `NonNull` pointer.
94        self.current_map =
95            self.maps.entry(hash).or_insert_with(|| HitMap::new(interp.original_bytecode())).into();
96    }
97}
98
99#[cfg(test)]
100pub(crate) mod tests {
101    use super::*;
102    use alloy_network::TransactionBuilder;
103    use alloy_primitives::{Address, Bytes, U256, keccak256};
104    use evm2::{
105        bytecode::Bytecode,
106        evm::{AccountInfo, InMemoryDB},
107    };
108    use foundry_evm_core::evm::{
109        EvmEnv, EvmFactoryFor, FoundryEvmFactory, FoundryEvmNetwork, FoundryTxConversion, SpecFor,
110        TransactionRequestFor, TypesFor,
111    };
112
113    pub(crate) const TARGET: Address = Address::with_last_byte(0xC0);
114
115    /// `if (calldataload(0) == 1) { jump(10) }; stop`, with a `JUMPDEST; STOP` at pc 10.
116    pub(crate) const BRANCH: &[u8] =
117        &[0x60, 0x00, 0x35, 0x60, 0x01, 0x14, 0x60, 0x0a, 0x57, 0x00, 0x5b, 0x00];
118
119    /// Calls `TARGET` running `code` with `input` on `FEN`'s default spec, returning the
120    /// transaction status and the inspector.
121    pub(crate) fn inspect<FEN: FoundryEvmNetwork, I: Inspector<TypesFor<FEN>> + 'static>(
122        code: &[u8],
123        input: U256,
124        inspector: I,
125    ) -> (bool, I)
126    where
127        TransactionRequestFor<FEN>: Default,
128    {
129        let caller = Address::with_last_byte(0xCA);
130        let chain_id = 31337;
131        let mut db = InMemoryDB::default();
132        db.insert_account_info(&caller, AccountInfo::default().with_balance(U256::from(1e18)));
133        db.insert_account_info(
134            &TARGET,
135            AccountInfo::default().with_code(Bytecode::new_legacy(Bytes::copy_from_slice(code))),
136        );
137        let factory = EvmFactoryFor::<FEN>::default();
138        let spec = SpecFor::<FEN>::default();
139        let env = EvmEnv::new(spec, factory.version(spec, chain_id), Default::default());
140        let mut evm = factory.create_evm(db, env);
141        evm.set_inspector(inspector);
142        let request = TransactionRequestFor::<FEN>::default()
143            .with_from(caller)
144            .with_to(TARGET)
145            .with_input(input.to_be_bytes::<32>())
146            .with_nonce(0)
147            .with_chain_id(chain_id)
148            .with_gas_limit(1_000_000)
149            .with_max_fee_per_gas(0)
150            .with_max_priority_fee_per_gas(0);
151        let tx = TypesFor::<FEN>::tx_from_request(request).unwrap();
152        let status = evm.transact(&tx).unwrap().commit().status;
153        (status, *evm.clear_inspector_as::<I>().unwrap())
154    }
155
156    fn line_coverage_suite<FEN: FoundryEvmNetwork>()
157    where
158        TransactionRequestFor<FEN>: Default,
159    {
160        for (input, pcs) in [(1, &[0, 2, 3, 5, 6, 8, 10, 11][..]), (2, &[0, 2, 3, 5, 6, 8, 9][..])]
161        {
162            let (status, collector) =
163                inspect::<FEN, _>(BRANCH, U256::from(input), LineCoverageCollector::default());
164            assert!(status);
165            let maps = collector.finish();
166            let map = &maps[&keccak256(BRANCH)];
167            let mut hits = map.iter().collect::<Vec<_>>();
168            hits.sort_unstable();
169            assert_eq!(hits, pcs.iter().map(|&pc| (pc, 1)).collect::<Vec<_>>());
170            // The small inputs are left-padded, so their selector is zero.
171            assert_eq!(map.selector_calls[&[0; 4]].without_value, 1);
172            assert_eq!(map.creations, 0);
173        }
174
175        // A successful `create(0, 0, 1)` of the init code `STOP` counts one creation.
176        let (status, collector) = inspect::<FEN, _>(
177            &[0x60, 0x01, 0x60, 0x00, 0x60, 0x00, 0xf0, 0x00],
178            U256::ZERO,
179            LineCoverageCollector::default(),
180        );
181        assert!(status);
182        assert_eq!(collector.finish()[&keccak256([0x00])].creations, 1);
183    }
184
185    #[test]
186    fn line_coverage() {
187        line_coverage_suite::<foundry_evm_core::evm::EthEvmNetwork>();
188        line_coverage_suite::<foundry_evm_core::evm::TempoEvmNetwork>();
189        #[cfg(feature = "optimism")]
190        line_coverage_suite::<foundry_evm_core::evm::OpEvmNetwork>();
191        #[cfg(feature = "base")]
192        line_coverage_suite::<foundry_evm_core::evm::BaseEvmNetwork>();
193        #[cfg(feature = "monad")]
194        line_coverage_suite::<foundry_evm_core::evm::MonadEvmNetwork>();
195    }
196}