Skip to main content

foundry_evm_coverage/
anchors.rs

1use 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
9/// Attempts to find anchors for the given items using the given source map and bytecode.
10pub 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
55/// Find an anchor representing the first opcode within the given source range.
56pub 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
75/// Finds the anchor corresponding to a branch item.
76///
77/// This finds the relevant anchors for a branch coverage item. These anchors
78/// are found using the bytecode of the contract in the range of the branching node.
79///
80/// For `IfStatement` nodes, the template is generally:
81/// ```text
82/// <condition>
83/// PUSH <ic if false>
84/// JUMPI
85/// <true branch>
86/// <...>
87/// <false branch>
88/// ```
89///
90/// For `assert` and `require`, the template is generally:
91///
92/// ```text
93/// PUSH <ic if true>
94/// JUMPI
95/// <revert>
96/// <...>
97/// <true branch>
98/// ```
99///
100/// This function will look for the last JUMPI instruction, backtrack to find the program
101/// counter of the first branch, and return an item for that program counter, and the
102/// program counter immediately after the JUMPI instruction.
103pub 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        // We found a push, so we do some PC -> IC translation accounting, but we also check if
112        // this push is coupled with the JUMPI we are interested in.
113
114        // Check if Opcode is PUSH
115        if (opcode::PUSH1..=opcode::PUSH32).contains(&inst.opcode.get()) {
116            let Some(element) = source_map.get(ic) else {
117                // NOTE(onbjerg): For some reason the last few bytes of the bytecode do not have
118                // a source map associated, so at that point we just stop searching
119                break;
120            };
121
122            // Check if we are in the source range we are interested in, and if the next opcode
123            // is a JUMPI
124            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                // We do not support program counters bigger than u32.
130                ensure!(push_size <= 4, "jump destination overflow");
131
132                // Convert the push bytes for the second branch's PC to a u32.
133                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                        // The first branch is the opcode directly after JUMPI
140                        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
151/// Calculates whether `element` is within the range of the target `location`.
152fn is_in_source_range(element: &SourceElement, location: &SourceLocation) -> bool {
153    // Source IDs must match.
154    let source_ids_match = element.index_i32() == location.source_id as i32;
155    if !source_ids_match {
156        return false;
157    }
158
159    // Needed because some source ranges in the source map mark the entire contract...
160    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}