summaryrefslogtreecommitdiff
path: root/plugins/warp/src/plugin/ffi.rs
blob: bb6fb483064a12d0810341b837de901b463a4fdd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
mod container;
mod file;
mod function;
mod processor;
mod ty;

use binaryninjacore_sys::{
    BNBasicBlock, BNBinaryView, BNFunction, BNLowLevelILFunction, BNPlatform,
};
use std::ffi::c_char;
use std::sync::{Arc, RwLock};
use uuid::Uuid;

use binaryninja::basic_block::{BasicBlock, BasicBlockType};
use binaryninja::function::{Function, NativeBlock};

use crate::cache::cached_function_guid;
use crate::container::{Container, SourceId};
use crate::convert::platform_to_target;
use crate::plugin::workflow::run_matcher;
use crate::{
    basic_block_guid, is_blacklisted_instruction, is_computed_variant_instruction,
    is_variant_instruction, relocatable_regions,
};
use binaryninja::binary_view::BinaryView;
use binaryninja::low_level_il::function::{LowLevelILFunction, Mutable, NonSSA};
use binaryninja::low_level_il::instruction::LowLevelInstructionIndex;
use binaryninja::platform::Platform;
use binaryninja::string::BnString;
use warp::r#type::guid::TypeGUID;
use warp::signature::basic_block::BasicBlockGUID;
use warp::signature::constraint::{Constraint, ConstraintGUID, UNRELATED_OFFSET};
use warp::signature::function::FunctionGUID;

/// [`SourceId`] is marked transparent to the underlying `[u8; 16]`, safe to use directly in FFI.
pub type BNWARPSource = SourceId;

/// [`BasicBlockGUID`] is marked transparent to the underlying `[u8; 16]`, safe to use directly in FFI.
pub type BNWARPBasicBlockGUID = BasicBlockGUID;

/// [`ConstraintGUID`] is marked transparent to the underlying `[u8; 16]`, safe to use directly in FFI.
pub type BNWARPConstraintGUID = ConstraintGUID;

/// [`FunctionGUID`] is marked transparent to the underlying `[u8; 16]`, safe to use directly in FFI.
pub type BNWARPFunctionGUID = FunctionGUID;

/// [`TypeGUID`] is marked transparent to the underlying `[u8; 16]`, safe to use directly in FFI.
pub type BNWARPTypeGUID = TypeGUID;

pub type BNWARPTarget = warp::target::Target;
pub type BNWARPFunction = warp::signature::function::Function;
pub type BNWARPContainer = RwLock<Box<dyn Container>>;
pub type BNWARPType = warp::r#type::Type;

// TODO: Some sort of callback for loading functions
// TODO: Be able to run matcher for a specific file
// TODO: Generate signatures for a file, return what?

#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct BNWARPConstraint {
    guid: BNWARPConstraintGUID,
    offset: i64,
}

impl From<BNWARPConstraint> for Constraint {
    fn from(constraint: BNWARPConstraint) -> Self {
        Constraint {
            guid: constraint.guid,
            offset: match constraint.offset {
                UNRELATED_OFFSET => None,
                _ => Some(constraint.offset),
            },
        }
    }
}

impl From<Constraint> for BNWARPConstraint {
    fn from(constraint: Constraint) -> Self {
        BNWARPConstraint {
            guid: constraint.guid,
            offset: constraint.offset.unwrap_or(UNRELATED_OFFSET),
        }
    }
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPUUIDGetString(uuid: *const Uuid) -> *mut c_char {
    let uuid_str = (*uuid).to_string();
    // NOTE: Leak the uuid string to be freed by BNFreeString
    BnString::into_raw(uuid_str.into())
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPUUIDFromString(uuid_str: *mut c_char, uuid: *mut Uuid) -> bool {
    if let Ok(uuid_str) = std::ffi::CStr::from_ptr(uuid_str).to_str() {
        if let Some(parsed_uuid) = Uuid::parse_str(uuid_str).ok() {
            *uuid = parsed_uuid;
            return true;
        }
    }
    false
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPUUIDEqual(a: *const Uuid, b: *const Uuid) -> bool {
    (*a) == (*b)
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPRunMatcher(view: *mut BNBinaryView) {
    let view = BinaryView::from_raw(view);
    run_matcher(&view)
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPGetBasicBlockGUID(
    basic_block: *mut BNBasicBlock,
    result: *mut BNWARPBasicBlockGUID,
) -> bool {
    let basic_block = unsafe { BasicBlock::from_raw(basic_block, NativeBlock::new()) };
    if basic_block.block_type() != BasicBlockType::Native {
        return false;
    }
    let function = basic_block.function();
    match function.lifted_il() {
        Ok(lifted_il) => {
            let relocatable_regions = relocatable_regions(&function.view());
            *result = basic_block_guid(&relocatable_regions, &basic_block, &lifted_il);
            true
        }
        Err(_) => false,
    }
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPGetAnalysisFunctionGUID(
    analysis_function: *mut BNFunction,
    result: *mut BNWARPFunctionGUID,
) -> bool {
    let function = unsafe { Function::from_raw(analysis_function) };
    match cached_function_guid(&function, || function.lifted_il().ok()) {
        Some(guid) => {
            *result = guid;
            true
        }
        None => false,
    }
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPIsLiftedInstructionVariant(
    analysis_function: *mut BNLowLevelILFunction,
    index: LowLevelInstructionIndex,
) -> bool {
    let lifted_il: LowLevelILFunction<Mutable, NonSSA> =
        unsafe { LowLevelILFunction::from_raw(analysis_function) };
    match lifted_il.instruction_from_index(index) {
        Some(instr) => {
            let Some(owner_function) = lifted_il.function() else {
                return false;
            };
            let relocatable_regions = relocatable_regions(&owner_function.view());
            is_variant_instruction(&relocatable_regions, &instr)
        }
        None => false,
    }
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPIsLowLevelInstructionComputedVariant(
    analysis_function: *mut BNLowLevelILFunction,
    index: LowLevelInstructionIndex,
) -> bool {
    let llil: LowLevelILFunction<Mutable, NonSSA> =
        unsafe { LowLevelILFunction::from_raw(analysis_function) };
    match llil.instruction_from_index(index) {
        Some(instr) => {
            let Some(owner_function) = llil.function() else {
                return false;
            };
            let relocatable_regions = relocatable_regions(&owner_function.view());
            is_computed_variant_instruction(&relocatable_regions, &instr)
        }
        None => false,
    }
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPIsLiftedInstructionBlacklisted(
    analysis_function: *mut BNLowLevelILFunction,
    index: LowLevelInstructionIndex,
) -> bool {
    let lifted_il: LowLevelILFunction<Mutable, NonSSA> =
        unsafe { LowLevelILFunction::from_raw(analysis_function) };
    match lifted_il.instruction_from_index(index) {
        Some(instr) => is_blacklisted_instruction(&instr),
        None => false,
    }
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPFreeUUIDList(uuids: *mut Uuid, count: usize) {
    let sources_ptr = std::ptr::slice_from_raw_parts_mut(uuids, count);
    let _ = unsafe { Box::from_raw(sources_ptr) };
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPGetTarget(platform: *mut BNPlatform) -> *mut BNWARPTarget {
    let platform = Platform::from_raw(platform);
    Arc::into_raw(Arc::new(platform_to_target(&platform))) as *mut BNWARPTarget
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPNewTargetReference(target: *mut BNWARPTarget) -> *mut BNWARPTarget {
    Arc::increment_strong_count(target);
    target
}

#[no_mangle]
pub unsafe extern "C" fn BNWARPFreeTargetReference(target: *mut BNWARPTarget) {
    if target.is_null() {
        return;
    }
    Arc::decrement_strong_count(target);
}