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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
|
// Copyright 2021 Vector 35 Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use binaryninjacore_sys::*;
use std::{fmt, mem, ptr, slice};
use crate::architecture::Architecture;
use crate::string::{BnStr, BnStrCompatible, BnString};
use crate::rc::*;
pub type ReferenceType = BNReferenceType;
pub type TypeClass = BNTypeClass;
pub type NamedTypeReferenceClass = BNNamedTypeReferenceClass;
//////////
// Type
#[derive(PartialEq, Eq, Hash)]
pub struct Type {
pub(crate) handle: *mut BNType,
pub(crate) confidence: u8,
}
impl Type {
pub(crate) unsafe fn from_raw(handle: *mut BNType) -> Self {
debug_assert!(!handle.is_null());
Self {
handle,
// TODO : Remove this field and and make Confidence<Type>
confidence: 255,
}
}
// TODO : Implement type builders (how I did with structures)
// pub(crate) unsafe fn from_builder(handle: *mut BNTypeBuilder) -> Self {
// debug_assert!(!handle.is_null());
// Self { handle }
// }
// TODO : Add this to a real doc_string:
// use binaryninja::types::Type;
// let bv = unsafe { BinaryView::from_raw(view) };
// let my_custom_type_1 = Type::named_int(5, false, "my_w");
// let my_custom_type_2 = Type::int(5, false);
// bv.define_user_type("int_1", &my_custom_type_1);
// bv.define_user_type("int_2", &my_custom_type_2);
pub fn void() -> Self {
unsafe { Type::from_raw(BNCreateVoidType()) }
}
pub fn bool() -> Self {
unsafe { Type::from_raw(BNCreateBoolType()) }
}
pub fn char() -> Self {
Type::int(1, true)
}
pub fn int(width: usize, is_signed: bool) -> Self {
let mut is_signed = BoolWithConfidence::new(is_signed, 0);
unsafe {
Type::from_raw(BNCreateIntegerType(
width,
&mut is_signed.0,
BnString::new("").as_ptr() as *mut _,
))
}
}
pub fn named_int<S: BnStrCompatible>(width: usize, is_signed: bool, alt_name: S) -> Self {
let mut is_signed = BoolWithConfidence::new(is_signed, 0);
// let alt_name = BnString::new(alt_name);
let alt_name = alt_name.as_bytes_with_nul(); // This segfaulted once, so the above version is there if we need to change to it, but in theory this is copied into a `const string&` on the C++ side; I'm just not 100% confident that a constant reference copies data
unsafe {
Type::from_raw(BNCreateIntegerType(
width,
&mut is_signed.0,
alt_name.as_ref().as_ptr() as _,
))
}
}
pub fn float(width: usize) -> Self {
unsafe {
Type::from_raw(BNCreateFloatType(
width,
BnString::new("").as_ptr() as *mut _,
))
}
}
pub fn named_float<S: BnStrCompatible>(width: usize, alt_name: S) -> Self {
// let alt_name = BnString::new(alt_name);
let alt_name = alt_name.as_bytes_with_nul(); // See same line in `named_int` above
unsafe { Type::from_raw(BNCreateFloatType(width, alt_name.as_ref().as_ptr() as _)) }
}
pub fn array(t: &Type, count: u64) -> Self {
let mut type_conf = TypeWithConfidence::new(&t, t.confidence);
unsafe { Type::from_raw(BNCreateArrayType(&mut type_conf.0, count)) }
}
pub fn structure_type(structure_type: &mut Structure) -> Self {
unsafe { Type::from_raw(BNCreateStructureType(structure_type.handle())) }
}
// TODO : Create enumeration type and finish implementing this
// pub fn enumeration<A: Architecture>(
// arch: A,
// enum_type: Enumeration,
// width: usize,
// is_signed: bool,
// ) -> Self {
// unsafe { Type::from_raw(BNCreateEnumerationType(arch, enum_type, width, is_signed)) }
// }
pub fn named_type(type_reference: NamedTypeReference) -> Self {
unsafe {
Type::from_raw(BNFinalizeTypeBuilder(BNCreateNamedTypeReferenceBuilder(
type_reference.handle,
0,
1,
)))
}
}
pub fn named_type_from_type<S: BnStrCompatible>(name: S, t: &Type) -> Self {
let mut name = QualifiedName::from(name);
unsafe {
Type::from_raw(BNFinalizeTypeBuilder(
BNCreateNamedTypeReferenceBuilderFromTypeAndId(
BnString::new("").as_ptr() as *mut _,
&mut name.0, // BNCreateNamedTypeReferenceBuilderFromTypeAndId copy's qualified the name
t.handle,
),
))
}
}
// TODO : BNCreateFunctionType
pub fn pointer<A: Architecture>(arch: &A, t: &Type) -> Self {
let mut is_const = BoolWithConfidence::new(false, 0);
let mut is_volatile = BoolWithConfidence::new(false, 0);
let mut type_conf = TypeWithConfidence::new(&t, t.confidence);
unsafe {
Type::from_raw(BNCreatePointerType(
arch.as_ref().0,
&mut type_conf.0,
&mut is_const.0,
&mut is_volatile.0,
ReferenceType::PointerReferenceType,
))
}
}
pub fn const_pointer<A: Architecture>(arch: &A, t: &Type) -> Self {
let mut is_const = BoolWithConfidence::new(true, 0);
let mut is_volatile = BoolWithConfidence::new(false, 0);
let mut type_conf = TypeWithConfidence::new(&t, t.confidence);
unsafe {
Type::from_raw(BNCreatePointerType(
arch.as_ref().0,
&mut type_conf.0,
&mut is_const.0,
&mut is_volatile.0,
ReferenceType::PointerReferenceType,
))
}
}
pub fn pointer_with_options<A: Architecture>(
arch: &A,
t: &Type,
is_const: bool,
is_volatile: bool,
ref_type: Option<ReferenceType>,
) -> Self {
let mut is_const = BoolWithConfidence::new(is_const, 0);
let mut is_volatile = BoolWithConfidence::new(is_volatile, 0);
let mut type_conf = TypeWithConfidence::new(&t, t.confidence);
unsafe {
Type::from_raw(BNCreatePointerType(
arch.as_ref().0,
&mut type_conf.0,
&mut is_const.0,
&mut is_volatile.0,
ref_type.unwrap_or_else(|| ReferenceType::PointerReferenceType),
))
}
}
pub fn generate_auto_demangled_type_id<'a, S: BnStrCompatible>(name: S) -> &'a BnStr {
let mut name = QualifiedName::from(name);
unsafe { BnStr::from_raw(BNGenerateAutoDemangledTypeId(&mut name.0)) }
}
}
impl fmt::Display for Type {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", unsafe {
BnString::from_raw(BNGetTypeString(self.handle, ptr::null_mut()))
})
}
}
unsafe impl Send for Type {}
unsafe impl Sync for Type {}
unsafe impl RefCountable for Type {
unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
Ref::new(Self {
handle: BNNewTypeReference(handle.handle),
confidence: handle.confidence,
})
}
unsafe fn dec_ref(handle: &Self) {
BNFreeType(handle.handle);
}
}
impl ToOwned for Type {
type Owned = Ref<Self>;
fn to_owned(&self) -> Self::Owned {
unsafe { RefCountable::inc_ref(self) }
}
}
///////////////
// Structure
#[derive(PartialEq, Eq, Hash)]
pub struct Structure {
pub builder: *mut BNStructureBuilder,
pub handle: Option<*mut BNStructure>,
}
// TODO : Throw asserts or return results?
impl Structure {
// TODO : Turn this into a real docstring
// // Includes
// use binaryninja::types::{Structure, Type};
// // Define struct, set size (in bytes)
// let mut my_custom_struct = Structure::new();
// my_custom_struct.set_width(17);
// // Create some fields for the struct
// let field_1 = Type::named_int(5, false, "my_weird_int_type");
// let field_2 = Type::int(4, false);
// let field_3 = Type::int(8, false);
// // Assign those fields
// my_custom_struct.append(&field_1, "field_4");
// my_custom_struct.insert(&field_1, "field_1", 0);
// my_custom_struct.insert(&field_2, "field_2", 5);
// my_custom_struct.insert(&field_3, "field_3", 9);
// // Convert structure to type
// let my_custom_structure_type = Type::structure_type(&mut my_custom_struct);
// // Add the struct to the binary view to use in analysis
// let bv = unsafe { BinaryView::from_raw(view) };
// bv.define_user_type("my_custom_struct", &my_custom_structure_type);
pub fn new() -> Self {
Structure {
builder: unsafe { BNCreateStructureBuilder() },
handle: None,
}
}
pub(crate) fn handle(&mut self) -> *mut BNStructure {
if let Some(handle) = self.handle {
handle
} else {
unsafe {
self.handle = Some(BNFinalizeStructureBuilder(self.builder));
BNFreeStructureBuilder(self.builder);
}
self.handle.unwrap()
}
}
pub fn set_width(&self, width: u64) {
assert!(self.handle.is_none());
unsafe {
BNSetStructureBuilderWidth(self.builder, width);
}
}
pub fn get_width(&self) -> u64 {
if let Some(structure_handle) = self.handle {
unsafe { BNGetStructureWidth(structure_handle) }
} else {
unsafe { BNGetStructureBuilderWidth(self.builder) }
}
}
pub fn append<S: BnStrCompatible>(&self, t: &Type, name: S) {
assert!(self.handle.is_none());
let mut type_conf = TypeWithConfidence::new(t, t.confidence);
let name = name.as_bytes_with_nul();
unsafe {
BNAddStructureBuilderMember(
self.builder,
&mut type_conf.0,
name.as_ref().as_ptr() as _,
);
}
}
pub fn insert<S: BnStrCompatible>(&self, t: &Type, name: S, offset: u64) {
assert!(self.handle.is_none());
let mut type_conf = TypeWithConfidence::new(t, t.confidence);
let name = name.as_bytes_with_nul();
unsafe {
BNAddStructureBuilderMemberAtOffset(
self.builder,
&mut type_conf.0,
name.as_ref().as_ptr() as _,
offset,
);
}
}
// TODO : The other methods in the python version (alignment, packed, type, members, remove, replace, etc)
}
// TODO : Use
// #[derive(PartialEq, Eq, Hash)]
// pub struct StructureMember {
// pub(crate) handle: *mut BNStructureMember,
// }
// impl StructureMember {
// // pub fn new() -> Self {}
// }
////////////////////////
// BoolWithConfidence
pub struct BoolWithConfidence(BNBoolWithConfidence);
impl BoolWithConfidence {
pub fn new(value: bool, confidence: u8) -> Self {
BoolWithConfidence(BNBoolWithConfidence { value, confidence })
}
}
////////////////////////
// TypeWithConfidence
pub struct TypeWithConfidence(BNTypeWithConfidence);
impl TypeWithConfidence {
pub fn new(t: &Type, confidence: u8) -> Self {
TypeWithConfidence(BNTypeWithConfidence {
type_: t.handle,
confidence,
})
}
}
////////////////////////
// NamedTypeReference
#[derive(PartialEq, Eq, Hash)]
pub struct NamedTypeReference {
pub(crate) handle: *mut BNNamedTypeReference,
}
impl NamedTypeReference {
pub fn new<S: BnStrCompatible>(
type_class: NamedTypeReferenceClass,
type_id: S,
mut name: QualifiedName,
) -> Self {
let type_id = type_id.as_bytes_with_nul();
NamedTypeReference {
handle: unsafe {
BNCreateNamedType(type_class, type_id.as_ref().as_ptr() as _, &mut name.0)
},
}
}
}
///////////////////
// QualifiedName
#[repr(transparent)]
pub struct QualifiedName(pub(crate) BNQualifiedName);
impl QualifiedName {
// TODO : I think this is bad
pub fn string(&self) -> String {
use std::ffi::CStr;
unsafe {
slice::from_raw_parts(self.0.name, self.0.nameCount)
.iter()
.map(|c| CStr::from_ptr(*c).to_string_lossy())
.collect::<Vec<_>>()
.join("::")
}
}
}
impl<S: BnStrCompatible> From<S> for QualifiedName {
fn from(name: S) -> Self {
let join = BnString::new("::");
let name = name.as_bytes_with_nul();
let mut list = vec![name.as_ref().as_ptr() as *const _];
QualifiedName(BNQualifiedName {
name: unsafe { BNAllocStringList(list.as_mut_ptr(), 1) },
join: join.into_raw(),
nameCount: 1,
})
}
}
impl Drop for QualifiedName {
fn drop(&mut self) {
unsafe {
BNFreeQualifiedName(&mut self.0);
}
}
}
//////////////////////////
// QualifiedNameAndType
#[repr(transparent)]
pub struct QualifiedNameAndType(pub(crate) BNQualifiedNameAndType);
impl QualifiedNameAndType {
pub fn name(&self) -> &QualifiedName {
unsafe { mem::transmute(&self.0.name) }
}
pub fn type_object(&self) -> Guard<Type> {
unsafe { Guard::new(Type::from_raw(self.0.type_), self) }
}
}
impl Drop for QualifiedNameAndType {
fn drop(&mut self) {
unsafe {
BNFreeQualifiedNameAndType(&mut self.0);
}
}
}
unsafe impl CoreOwnedArrayProvider for QualifiedNameAndType {
type Raw = BNQualifiedNameAndType;
type Context = ();
unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
BNFreeTypeList(raw, count);
}
}
unsafe impl<'a> CoreOwnedArrayWrapper<'a> for QualifiedNameAndType {
type Wrapped = &'a QualifiedNameAndType;
unsafe fn wrap_raw(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped {
mem::transmute(raw)
}
}
|