binaryninja/low_level_il/
function.rs1use std::fmt::Debug;
16use std::hash::{Hash, Hasher};
17use std::marker::PhantomData;
18
19use binaryninjacore_sys::*;
20
21use crate::architecture::{CoreArchitecture, CoreFlag};
22use crate::basic_block::BasicBlock;
23use crate::function::Function;
24use crate::low_level_il::block::LowLevelILBlock;
25use crate::rc::*;
26use crate::variable::RegisterValue;
27
28use super::*;
29
30#[derive(Copy, Clone, Debug)]
31pub struct Mutable;
32#[derive(Copy, Clone, Debug)]
33pub struct Finalized;
34
35pub trait FunctionMutability: 'static + Debug + Copy {}
36impl FunctionMutability for Mutable {}
37impl FunctionMutability for Finalized {}
38
39#[derive(Copy, Clone, Debug)]
40pub struct SSA;
41#[derive(Copy, Clone, Debug)]
42pub struct NonSSA;
43
44pub trait FunctionForm: 'static + Debug + Copy {}
45impl FunctionForm for SSA {}
46impl FunctionForm for NonSSA {}
47
48pub struct LowLevelILFunction<M: FunctionMutability, F: FunctionForm> {
49 pub(crate) handle: *mut BNLowLevelILFunction,
50 arch: Option<CoreArchitecture>,
51 _mutability: PhantomData<M>,
52 _form: PhantomData<F>,
53}
54
55impl<M, F> LowLevelILFunction<M, F>
56where
57 M: FunctionMutability,
58 F: FunctionForm,
59{
60 pub(crate) unsafe fn from_raw_with_arch(
61 handle: *mut BNLowLevelILFunction,
62 arch: Option<CoreArchitecture>,
63 ) -> Self {
64 debug_assert!(!handle.is_null());
65
66 Self {
67 handle,
68 arch,
69 _mutability: PhantomData,
70 _form: PhantomData,
71 }
72 }
73
74 pub unsafe fn from_raw(handle: *mut BNLowLevelILFunction) -> Self {
75 Self::from_raw_with_arch(handle, None)
76 }
77
78 pub(crate) unsafe fn ref_from_raw_with_arch(
79 handle: *mut BNLowLevelILFunction,
80 arch: Option<CoreArchitecture>,
81 ) -> Ref<Self> {
82 debug_assert!(!handle.is_null());
83 Ref::new(Self::from_raw_with_arch(handle, arch))
84 }
85
86 pub(crate) unsafe fn ref_from_raw(handle: *mut BNLowLevelILFunction) -> Ref<Self> {
87 Self::ref_from_raw_with_arch(handle, None)
88 }
89
90 pub(crate) fn arch(&self) -> CoreArchitecture {
91 match self.arch {
93 None => self.function().unwrap().arch(),
94 Some(arch) => arch,
95 }
96 }
97
98 pub fn instruction_at<L: Into<Location>>(
99 &self,
100 loc: L,
101 ) -> Option<LowLevelILInstruction<'_, M, F>> {
102 Some(LowLevelILInstruction::new(
103 self,
104 self.instruction_index_at(loc)?,
105 ))
106 }
107
108 pub fn instructions_at<L: Into<Location>>(
110 &self,
111 loc: L,
112 ) -> Vec<LowLevelILInstruction<'_, M, F>> {
113 let loc = loc.into();
114 self.instruction_indexes_at(loc)
115 .iter()
116 .map(|idx| LowLevelILInstruction::new(self, idx))
117 .collect()
118 }
119
120 pub fn instruction_index_at<L: Into<Location>>(
121 &self,
122 loc: L,
123 ) -> Option<LowLevelInstructionIndex> {
124 use binaryninjacore_sys::BNLowLevelILGetInstructionStart;
125 let loc: Location = loc.into();
126 let arch = loc.arch.unwrap_or_else(|| self.arch());
128 let instr_idx =
129 unsafe { BNLowLevelILGetInstructionStart(self.handle, arch.handle, loc.addr) };
130 if instr_idx >= self.instruction_count() {
132 None
133 } else {
134 Some(LowLevelInstructionIndex(instr_idx))
135 }
136 }
137
138 pub fn instruction_indexes_at<L: Into<Location>>(
139 &self,
140 loc: L,
141 ) -> Array<LowLevelInstructionIndex> {
142 let loc: Location = loc.into();
143 let arch = loc.arch.unwrap_or_else(|| self.arch());
145 let mut count = 0;
146 let indexes = unsafe {
147 BNLowLevelILGetInstructionsAt(self.handle, arch.handle, loc.addr, &mut count)
148 };
149 unsafe { Array::new(indexes, count, ()) }
150 }
151
152 pub fn instruction_from_index(
153 &self,
154 index: LowLevelInstructionIndex,
155 ) -> Option<LowLevelILInstruction<'_, M, F>> {
156 if index.0 >= self.instruction_count() {
157 None
158 } else {
159 Some(LowLevelILInstruction::new(self, index))
160 }
161 }
162
163 pub fn instruction_count(&self) -> usize {
164 unsafe {
165 use binaryninjacore_sys::BNGetLowLevelILInstructionCount;
166 BNGetLowLevelILInstructionCount(self.handle)
167 }
168 }
169
170 pub fn expression_count(&self) -> usize {
171 unsafe {
172 use binaryninjacore_sys::BNGetLowLevelILExprCount;
173 BNGetLowLevelILExprCount(self.handle)
174 }
175 }
176
177 pub fn function(&self) -> Option<Ref<Function>> {
178 unsafe {
179 let func = BNGetLowLevelILOwnerFunction(self.handle);
180 if func.is_null() {
181 return None;
182 }
183 Some(Function::ref_from_raw(func))
184 }
185 }
186
187 pub fn basic_blocks(&self) -> Array<BasicBlock<LowLevelILBlock<'_, M, F>>> {
188 use binaryninjacore_sys::BNGetLowLevelILBasicBlockList;
189
190 unsafe {
191 let mut count = 0;
192 let blocks = BNGetLowLevelILBasicBlockList(self.handle, &mut count);
193 let context = LowLevelILBlock { function: self };
194 Array::new(blocks, count, context)
195 }
196 }
197
198 pub fn basic_block_containing_index(
202 &self,
203 index: LowLevelInstructionIndex,
204 ) -> Option<Ref<BasicBlock<LowLevelILBlock<'_, M, F>>>> {
205 let block = unsafe { BNGetLowLevelILBasicBlockForInstruction(self.handle, index.0) };
206 if block.is_null() {
207 None
208 } else {
209 Some(unsafe { BasicBlock::ref_from_raw(block, LowLevelILBlock { function: self }) })
210 }
211 }
212}
213
214impl<M: FunctionMutability> LowLevelILFunction<M, NonSSA> {
215 pub fn ssa_form(&self) -> Option<Ref<LowLevelILFunction<M, SSA>>> {
219 let handle = unsafe { BNGetLowLevelILSSAForm(self.handle) };
220 if handle.is_null() {
221 return None;
222 }
223 Some(unsafe { LowLevelILFunction::ref_from_raw(handle) })
224 }
225
226 pub fn generate_ssa_form(&self) {
242 use binaryninjacore_sys::BNGenerateLowLevelILSSAForm;
243 if self.function().is_some() {
245 unsafe { BNGenerateLowLevelILSSAForm(self.handle) };
246 }
247 }
248}
249
250impl LowLevelILFunction<Mutable, NonSSA> {
252 pub fn new(arch: CoreArchitecture, source_func: Option<Function>) -> Ref<Self> {
256 use binaryninjacore_sys::BNCreateLowLevelILFunction;
257
258 let handle = unsafe {
259 match source_func {
260 Some(func) => BNCreateLowLevelILFunction(arch.handle, func.handle),
261 None => BNCreateLowLevelILFunction(arch.handle, std::ptr::null_mut()),
262 }
263 };
264
265 assert!(!handle.is_null());
267
268 unsafe { Self::ref_from_raw_with_arch(handle, Some(arch)) }
269 }
270}
271
272impl Ref<LowLevelILFunction<Mutable, NonSSA>> {
273 pub fn finalized(self) -> Ref<LowLevelILFunction<Finalized, NonSSA>> {
289 unsafe {
290 BNFinalizeLowLevelILFunction(self.handle);
291 LowLevelILFunction::from_raw_with_arch(self.handle, self.arch).to_owned()
293 }
294 }
295}
296
297impl<M: FunctionMutability> LowLevelILFunction<M, SSA> {
298 #[must_use]
300 pub fn get_ssa_register_uses<R: ArchReg>(
301 &self,
302 reg: impl AsRef<LowLevelILSSARegister<R>>,
303 ) -> Vec<LowLevelILInstruction<'_, M, SSA>> {
304 use binaryninjacore_sys::BNGetLowLevelILSSARegisterUses;
305 let reg = reg.as_ref();
306 let mut count = 0;
307 let instrs = unsafe {
308 BNGetLowLevelILSSARegisterUses(
309 self.handle,
310 reg.id().into(),
311 reg.version as usize,
312 &mut count,
313 )
314 };
315 let result = unsafe { std::slice::from_raw_parts(instrs, count) }
316 .iter()
317 .map(|idx| LowLevelILInstruction::new(self, LowLevelInstructionIndex(*idx)))
318 .collect();
319 unsafe { BNFreeILInstructionList(instrs) };
320 result
321 }
322
323 #[must_use]
325 pub fn get_ssa_register_definition<R: ArchReg>(
326 &self,
327 reg: impl AsRef<LowLevelILSSARegister<R>>,
328 ) -> Option<LowLevelILInstruction<'_, M, SSA>> {
329 use binaryninjacore_sys::BNGetLowLevelILSSARegisterDefinition;
330 let reg = reg.as_ref();
331 let instr_idx = unsafe {
332 BNGetLowLevelILSSARegisterDefinition(self.handle, reg.id().into(), reg.version as usize)
333 };
334 self.instruction_from_index(LowLevelInstructionIndex(instr_idx))
335 }
336
337 #[must_use]
339 pub fn get_ssa_register_value<R: ArchReg>(
340 &self,
341 reg: impl AsRef<LowLevelILSSARegister<R>>,
342 ) -> Option<RegisterValue> {
343 let reg = reg.as_ref();
344 let value = unsafe {
345 BNGetLowLevelILSSARegisterValue(self.handle, reg.id().into(), reg.version as usize)
346 };
347 if value.state == BNRegisterValueType::UndeterminedValue {
348 return None;
349 }
350 Some(value.into())
351 }
352
353 #[must_use]
355 pub fn get_ssa_flag_value(&self, flag: &LowLevelILSSAFlag<CoreFlag>) -> Option<RegisterValue> {
356 let value = unsafe {
357 BNGetLowLevelILSSAFlagValue(self.handle, flag.flag.id().0, flag.version as usize)
358 };
359 if value.state == BNRegisterValueType::UndeterminedValue {
360 return None;
361 }
362 Some(value.into())
363 }
364}
365
366impl<M, F> ToOwned for LowLevelILFunction<M, F>
367where
368 M: FunctionMutability,
369 F: FunctionForm,
370{
371 type Owned = Ref<Self>;
372
373 fn to_owned(&self) -> Self::Owned {
374 unsafe { RefCountable::inc_ref(self) }
375 }
376}
377
378unsafe impl<M, F> RefCountable for LowLevelILFunction<M, F>
379where
380 M: FunctionMutability,
381 F: FunctionForm,
382{
383 unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
384 Ref::new(Self {
385 handle: BNNewLowLevelILFunctionReference(handle.handle),
386 arch: handle.arch,
387 _mutability: PhantomData,
388 _form: PhantomData,
389 })
390 }
391
392 unsafe fn dec_ref(handle: &Self) {
393 BNFreeLowLevelILFunction(handle.handle);
394 }
395}
396
397impl<M, F> Debug for LowLevelILFunction<M, F>
398where
399 M: FunctionMutability,
400 F: FunctionForm,
401{
402 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
403 f.debug_struct("LowLevelILFunction")
404 .field("arch", &self.arch())
405 .field("instruction_count", &self.instruction_count())
406 .field("expression_count", &self.expression_count())
407 .finish()
408 }
409}
410
411unsafe impl<M: FunctionMutability, F: FunctionForm> Send for LowLevelILFunction<M, F> {}
412unsafe impl<M: FunctionMutability, F: FunctionForm> Sync for LowLevelILFunction<M, F> {}
413
414impl<M: FunctionMutability, F: FunctionForm> Eq for LowLevelILFunction<M, F> {}
415
416impl<M: FunctionMutability, F: FunctionForm> PartialEq for LowLevelILFunction<M, F> {
417 fn eq(&self, rhs: &Self) -> bool {
418 self.function().eq(&rhs.function())
419 }
420}
421
422impl<M: FunctionMutability, F: FunctionForm> Hash for LowLevelILFunction<M, F> {
423 fn hash<H: Hasher>(&self, state: &mut H) {
424 self.function().hash(state)
425 }
426}