foundry_evm_coverage/
anchors.rs1use super::{CoverageItemKind, ItemAnchor, SourceLocation};
2use crate::analysis::SourceAnalysis;
3use alloy_primitives::map::rustc_hash::FxHashSet;
4use eyre::ensure;
5use foundry_compilers::artifacts::sourcemap::{SourceElement, SourceMap};
6use foundry_evm_core::{bytecode::InstIter, ic::IcPcMap};
7use revm::bytecode::opcode;
8
9pub fn find_anchors(
11 bytecode: &[u8],
12 source_map: &SourceMap,
13 ic_pc_map: &IcPcMap,
14 analysis: &SourceAnalysis,
15) -> Vec<ItemAnchor> {
16 let mut seen_sources = FxHashSet::default();
17 source_map
18 .iter()
19 .filter_map(|element| element.index())
20 .filter(|&source| seen_sources.insert(source))
21 .flat_map(|source| analysis.items_for_source_enumerated(source))
22 .filter_map(|(item_id, item)| {
23 let anchor_loc = item.anchor_loc.as_ref().unwrap_or(&item.loc);
24 match item.kind {
25 CoverageItemKind::Branch { path_id, is_first_opcode: true, .. }
26 if item.anchor_loc.is_some() =>
27 {
28 find_anchor_simple(source_map, ic_pc_map, item_id, anchor_loc).or_else(|_| {
29 find_anchor_branch(bytecode, source_map, item_id, &item.loc).map(
30 |anchors| match path_id {
31 0 => anchors.0,
32 1 => anchors.1,
33 _ => panic!("too many path IDs for branch"),
34 },
35 )
36 })
37 }
38 CoverageItemKind::Branch { path_id, is_first_opcode: false, .. } => {
39 find_anchor_branch(bytecode, source_map, item_id, anchor_loc).map(|anchors| {
40 match path_id {
41 0 => anchors.0,
42 1 => anchors.1,
43 _ => panic!("too many path IDs for branch"),
44 }
45 })
46 }
47 _ => find_anchor_simple(source_map, ic_pc_map, item_id, anchor_loc),
48 }
49 .inspect_err(|err| warn!(%item, %err, "could not find anchor"))
50 .ok()
51 })
52 .collect()
53}
54
55pub fn find_anchor_simple(
57 source_map: &SourceMap,
58 ic_pc_map: &IcPcMap,
59 item_id: u32,
60 loc: &SourceLocation,
61) -> eyre::Result<ItemAnchor> {
62 let instruction =
63 source_map.iter().position(|element| is_in_source_range(element, loc)).ok_or_else(
64 || eyre::eyre!("Could not find anchor: No matching instruction in range {loc}"),
65 )?;
66
67 Ok(ItemAnchor {
68 instruction: ic_pc_map.get(instruction as u32).ok_or_else(|| {
69 eyre::eyre!("We found an anchor, but we can't translate it to a program counter")
70 })?,
71 item_id,
72 })
73}
74
75pub fn find_anchor_branch(
104 bytecode: &[u8],
105 source_map: &SourceMap,
106 item_id: u32,
107 loc: &SourceLocation,
108) -> eyre::Result<(ItemAnchor, ItemAnchor)> {
109 let mut anchors: Option<(ItemAnchor, ItemAnchor)> = None;
110 for (ic, (pc, inst)) in InstIter::new(bytecode).with_pc().enumerate() {
111 if (opcode::PUSH1..=opcode::PUSH32).contains(&inst.opcode.get()) {
116 let Some(element) = source_map.get(ic) else {
117 break;
120 };
121
122 let next_pc = pc + inst.immediate.len() + 1;
125 let push_size = inst.immediate.len();
126 if bytecode.get(next_pc).copied() == Some(opcode::JUMPI)
127 && is_in_source_range(element, loc)
128 {
129 ensure!(push_size <= 4, "jump destination overflow");
131
132 let mut pc_bytes = [0u8; 4];
134 pc_bytes[4 - push_size..].copy_from_slice(inst.immediate);
135 let pc_jump = u32::from_be_bytes(pc_bytes);
136 anchors = Some((
137 ItemAnchor {
138 item_id,
139 instruction: (next_pc + 1) as u32,
141 },
142 ItemAnchor { item_id, instruction: pc_jump },
143 ));
144 }
145 }
146 }
147
148 anchors.ok_or_else(|| eyre::eyre!("Could not detect branches in source: {}", loc))
149}
150
151fn is_in_source_range(element: &SourceElement, location: &SourceLocation) -> bool {
153 let source_ids_match = element.index_i32() == location.source_id as i32;
155 if !source_ids_match {
156 return false;
157 }
158
159 let is_within_start = element.offset() >= location.bytes.start;
161 if !is_within_start {
162 return false;
163 }
164
165 let start_of_ranges = location.bytes.start.max(element.offset());
166 let end_of_ranges =
167 (location.bytes.start + location.len()).min(element.offset() + element.length());
168 let within_ranges = start_of_ranges <= end_of_ranges;
169 if !within_ranges {
170 return false;
171 }
172
173 true
174}