binaryninja/low_level_il/
block.rs

1// Copyright 2021-2025 Vector 35 Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt::Debug;
16use std::ops::Range;
17
18use crate::basic_block::{BasicBlock, BlockContext};
19
20use super::*;
21
22#[derive(Copy, Clone)]
23pub struct LowLevelILBlock<'func, M, F>
24where
25    M: FunctionMutability,
26    F: FunctionForm,
27{
28    pub(crate) function: &'func LowLevelILFunction<M, F>,
29}
30
31impl<'func, M, F> BlockContext for LowLevelILBlock<'func, M, F>
32where
33    M: FunctionMutability,
34    F: FunctionForm,
35{
36    type Instruction = LowLevelILInstruction<'func, M, F>;
37    type InstructionIndex = LowLevelInstructionIndex;
38    type Iter = LowLevelILBlockIter<'func, M, F>;
39
40    fn start(&self, block: &BasicBlock<Self>) -> LowLevelILInstruction<'func, M, F> {
41        self.function
42            .instruction_from_index(block.start_index())
43            .unwrap()
44    }
45
46    fn iter(&self, block: &BasicBlock<Self>) -> LowLevelILBlockIter<'func, M, F> {
47        LowLevelILBlockIter {
48            function: self.function,
49            range: (block.start_index().0)..(block.end_index().0),
50        }
51    }
52}
53
54impl<M, F> Debug for LowLevelILBlock<'_, M, F>
55where
56    M: FunctionMutability,
57    F: FunctionForm,
58{
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        f.debug_struct("LowLevelILBlock")
61            .field("function", &self.function)
62            .finish()
63    }
64}
65
66pub struct LowLevelILBlockIter<'func, M, F>
67where
68    M: FunctionMutability,
69    F: FunctionForm,
70{
71    function: &'func LowLevelILFunction<M, F>,
72    // TODO: Once step_trait is stable we can do Range<InstructionIndex>
73    range: Range<usize>,
74}
75
76impl<'func, M, F> Iterator for LowLevelILBlockIter<'func, M, F>
77where
78    M: FunctionMutability,
79    F: FunctionForm,
80{
81    type Item = LowLevelILInstruction<'func, M, F>;
82
83    fn next(&mut self) -> Option<Self::Item> {
84        self.range
85            .next()
86            .map(LowLevelInstructionIndex)
87            .and_then(|idx| self.function.instruction_from_index(idx))
88    }
89}