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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
|
// Copyright 2021-2026 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.
//! The model for representing types in Binary Ninja.
//!
//! [`Type`]'s are fundamental to analysis. With types, you can influence how decompilation resolves accesses,
//! renders data, and tell the analysis of properties such as volatility and constness.
//!
//! Types are typically stored within a [`BinaryView`], [`TypeArchive`] or a [`TypeLibrary`].
//!
//! Types can be created using the [`TypeBuilder`] or one of the convenience functions. Another way
//! to create a type is with a [`TypeParser`] if you have C type definitions.
//!
//! Some interfaces may expect to be passed a [`TypeContainer`] which itself does not store any type
//! information, rather a generic interface to query for types by name or by id.
pub mod archive;
pub mod container;
pub mod enumeration;
pub mod library;
pub mod parser;
pub mod printer;
pub mod structure;
use binaryninjacore_sys::*;
use crate::{
architecture::{Architecture, Register, RegisterId},
binary_view::BinaryView,
calling_convention::CoreCallingConvention,
rc::*,
string::{BnString, IntoCStr},
};
use crate::confidence::{Conf, MAX_CONFIDENCE, MIN_CONFIDENCE};
use crate::string::raw_to_string;
use crate::variable::{Variable, VariableSourceType};
use std::num::NonZeroUsize;
use std::{
collections::HashSet,
fmt::{Debug, Display, Formatter},
hash::{Hash, Hasher},
iter::IntoIterator,
};
pub use archive::{TypeArchive, TypeArchiveId, TypeArchiveSnapshotId};
pub use container::TypeContainer;
pub use enumeration::{Enumeration, EnumerationBuilder, EnumerationMember};
pub use library::TypeLibrary;
pub use parser::{
CoreTypeParser, ParsedType, TypeParser, TypeParserError, TypeParserErrorSeverity,
TypeParserResult,
};
pub use printer::{CoreTypePrinter, TypePrinter};
pub use structure::{
BaseStructure, InheritedStructureMember, Structure, StructureBuilder, StructureMember,
};
#[deprecated(note = "Use crate::qualified_name::QualifiedName instead")]
// Re-export QualifiedName so that we do not break public consumers.
pub use crate::qualified_name::QualifiedName;
pub type StructureType = BNStructureVariant;
pub type ReferenceType = BNReferenceType;
pub type TypeClass = BNTypeClass;
pub type NamedTypeReferenceClass = BNNamedTypeReferenceClass;
pub type MemberAccess = BNMemberAccess;
pub type MemberScope = BNMemberScope;
pub type IntegerDisplayType = BNIntegerDisplayType;
pub type PointerBaseType = BNPointerBaseType;
#[derive(PartialEq, Eq, Hash)]
pub struct TypeBuilder {
pub(crate) handle: *mut BNTypeBuilder,
}
impl TypeBuilder {
pub fn new(t: &Type) -> Self {
unsafe { Self::from_raw(BNCreateTypeBuilderFromType(t.handle)) }
}
pub(crate) unsafe fn from_raw(handle: *mut BNTypeBuilder) -> Self {
debug_assert!(!handle.is_null());
Self { handle }
}
/// Turn the [`TypeBuilder`] into a [`Type`].
pub fn finalize(&self) -> Ref<Type> {
unsafe { Type::ref_from_raw(BNFinalizeTypeBuilder(self.handle)) }
}
pub fn set_can_return<T: Into<Conf<bool>>>(&self, value: T) -> &Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNSetFunctionTypeBuilderCanReturn(self.handle, &mut bool_with_confidence) };
self
}
pub fn set_pure<T: Into<Conf<bool>>>(&self, value: T) -> &Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNSetTypeBuilderPure(self.handle, &mut bool_with_confidence) };
self
}
pub fn set_const<T: Into<Conf<bool>>>(&self, value: T) -> &Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNTypeBuilderSetConst(self.handle, &mut bool_with_confidence) };
self
}
pub fn set_volatile<T: Into<Conf<bool>>>(&self, value: T) -> &Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNTypeBuilderSetVolatile(self.handle, &mut bool_with_confidence) };
self
}
/// Set the width of the type.
///
/// Typically only done for named type references, which will not have their width set otherwise.
pub fn set_width(&self, width: usize) -> &Self {
unsafe { BNTypeBuilderSetWidth(self.handle, width) }
self
}
/// Set the alignment of the type.
///
/// Typically only done for named type references, which will not have their alignment set otherwise.
pub fn set_alignment(&self, alignment: usize) -> &Self {
unsafe { BNTypeBuilderSetAlignment(self.handle, alignment) }
self
}
pub fn set_pointer_base(&self, base_type: PointerBaseType, base_offset: i64) -> &Self {
unsafe { BNSetTypeBuilderPointerBase(self.handle, base_type, base_offset) }
self
}
pub fn set_child_type<'a, T: Into<Conf<&'a Type>>>(&self, ty: T) -> &Self {
let mut type_with_confidence = Conf::<&Type>::into_raw(ty.into());
unsafe { BNTypeBuilderSetChildType(self.handle, &mut type_with_confidence) };
self
}
/// This is an alias for [`Self::set_child_type`].
pub fn set_target<'a, T: Into<Conf<&'a Type>>>(&self, ty: T) -> &Self {
self.set_child_type(ty)
}
/// This is an alias for [`Self::set_child_type`].
pub fn set_element_type<'a, T: Into<Conf<&'a Type>>>(&self, ty: T) -> &Self {
self.set_child_type(ty)
}
/// This is an alias for [`Self::set_child_type`].
pub fn set_return_value<'a, T: Into<Conf<&'a Type>>>(&self, ty: T) -> &Self {
self.set_child_type(ty)
}
pub fn set_signed<T: Into<Conf<bool>>>(&self, value: T) -> &Self {
let mut bool_with_confidence = value.into().into();
unsafe { BNTypeBuilderSetSigned(self.handle, &mut bool_with_confidence) };
self
}
pub fn set_integer_display_type(&self, display_type: IntegerDisplayType) -> &Self {
unsafe { BNSetIntegerTypeDisplayType(self.handle, display_type) };
self
}
// Readable properties
pub fn type_class(&self) -> TypeClass {
unsafe { BNGetTypeBuilderClass(self.handle) }
}
pub fn width(&self) -> u64 {
unsafe { BNGetTypeBuilderWidth(self.handle) }
}
pub fn alignment(&self) -> usize {
unsafe { BNGetTypeBuilderAlignment(self.handle) }
}
pub fn is_signed(&self) -> Conf<bool> {
unsafe { BNIsTypeBuilderSigned(self.handle).into() }
}
pub fn integer_display_type(&self) -> IntegerDisplayType {
self.finalize().integer_display_type()
}
pub fn is_const(&self) -> Conf<bool> {
unsafe { BNIsTypeBuilderConst(self.handle).into() }
}
pub fn is_volatile(&self) -> Conf<bool> {
unsafe { BNIsTypeBuilderVolatile(self.handle).into() }
}
pub fn is_floating_point(&self) -> bool {
unsafe { BNIsTypeBuilderFloatingPoint(self.handle) }
}
pub fn child_type(&self) -> Option<Conf<Ref<Type>>> {
let raw_target = unsafe { BNGetTypeBuilderChildType(self.handle) };
match raw_target.type_.is_null() {
false => Some(Conf::<Ref<Type>>::from_owned_raw(raw_target)),
true => None,
}
}
/// This is an alias for [`Self::child_type`].
pub fn target(&self) -> Option<Conf<Ref<Type>>> {
self.child_type()
}
/// This is an alias for [`Self::child_type`].
pub fn element_type(&self) -> Option<Conf<Ref<Type>>> {
self.child_type()
}
/// This is an alias for [`Self::child_type`].
pub fn return_value(&self) -> Option<Conf<Ref<Type>>> {
self.child_type()
}
pub fn calling_convention(&self) -> Option<Conf<Ref<CoreCallingConvention>>> {
let raw_convention_confidence = unsafe { BNGetTypeBuilderCallingConvention(self.handle) };
match raw_convention_confidence.convention.is_null() {
false => Some(Conf::<Ref<CoreCallingConvention>>::from_owned_raw(
raw_convention_confidence,
)),
true => None,
}
}
pub fn parameters(&self) -> Option<Vec<FunctionParameter>> {
unsafe {
let mut count = 0;
let raw_parameters_ptr = BNGetTypeBuilderParameters(self.handle, &mut count);
match raw_parameters_ptr.is_null() {
false => {
let raw_parameters = std::slice::from_raw_parts(raw_parameters_ptr, count);
let parameters = raw_parameters
.iter()
.map(FunctionParameter::from_raw)
.collect();
BNFreeTypeParameterList(raw_parameters_ptr, count);
Some(parameters)
}
true => None,
}
}
}
pub fn has_variable_arguments(&self) -> Conf<bool> {
unsafe { BNTypeBuilderHasVariableArguments(self.handle).into() }
}
pub fn can_return(&self) -> Conf<bool> {
unsafe { BNFunctionTypeBuilderCanReturn(self.handle).into() }
}
pub fn pure(&self) -> Conf<bool> {
unsafe { BNIsTypeBuilderPure(self.handle).into() }
}
// TODO: This naming is problematic... rename to `as_structure`?
// TODO: We wouldn't need these sort of functions if we destructured `Type`...
pub fn get_structure(&self) -> Option<Ref<Structure>> {
let raw_struct_ptr = unsafe { BNGetTypeBuilderStructure(self.handle) };
match raw_struct_ptr.is_null() {
false => Some(unsafe { Structure::ref_from_raw(raw_struct_ptr) }),
true => None,
}
}
// TODO: This naming is problematic... rename to `as_enumeration`?
// TODO: We wouldn't need these sort of functions if we destructured `Type`...
pub fn get_enumeration(&self) -> Option<Ref<Enumeration>> {
let raw_enum_ptr = unsafe { BNGetTypeBuilderEnumeration(self.handle) };
match raw_enum_ptr.is_null() {
false => Some(unsafe { Enumeration::ref_from_raw(raw_enum_ptr) }),
true => None,
}
}
// TODO: This naming is problematic... rename to `as_named_type_reference`?
// TODO: We wouldn't need these sort of functions if we destructured `Type`...
pub fn get_named_type_reference(&self) -> Option<Ref<NamedTypeReference>> {
let raw_type_ref_ptr = unsafe { BNGetTypeBuilderNamedTypeReference(self.handle) };
match raw_type_ref_ptr.is_null() {
false => Some(unsafe { NamedTypeReference::ref_from_raw(raw_type_ref_ptr) }),
true => None,
}
}
pub fn count(&self) -> u64 {
unsafe { BNGetTypeBuilderElementCount(self.handle) }
}
pub fn offset(&self) -> u64 {
unsafe { BNGetTypeBuilderOffset(self.handle) }
}
pub fn stack_adjustment(&self) -> Conf<i64> {
unsafe { BNGetTypeBuilderStackAdjustment(self.handle).into() }
}
pub fn pointer_base_type(&self) -> PointerBaseType {
unsafe { BNTypeBuilderGetPointerBaseType(self.handle) }
}
pub fn pointer_base_offset(&self) -> i64 {
unsafe { BNTypeBuilderGetPointerBaseOffset(self.handle) }
}
// TODO : This and properties
// pub fn tokens(&self) -> ? {}
/// Create a void [`TypeBuilder`]. Analogous to [`Type::void`].
pub fn void() -> Self {
unsafe { Self::from_raw(BNCreateVoidTypeBuilder()) }
}
/// Create a bool [`TypeBuilder`]. Analogous to [`Type::bool`].
pub fn bool() -> Self {
unsafe { Self::from_raw(BNCreateBoolTypeBuilder()) }
}
/// Create a signed one byte integer [`TypeBuilder`]. Analogous to [`Type::char`].
pub fn char() -> Self {
Self::int(1, true)
}
/// Create an integer [`TypeBuilder`] with the given width and signedness. Analogous to [`Type::int`].
pub fn int(width: usize, is_signed: bool) -> Self {
let mut is_signed = Conf::new(is_signed, MAX_CONFIDENCE).into();
unsafe {
Self::from_raw(BNCreateIntegerTypeBuilder(
width,
&mut is_signed,
c"".as_ptr() as _,
))
}
}
/// Create an integer [`TypeBuilder`] with the given width and signedness and an alternative name.
/// Analogous to [`Type::named_int`].
pub fn named_int(width: usize, is_signed: bool, alt_name: &str) -> Self {
let mut is_signed = Conf::new(is_signed, MAX_CONFIDENCE).into();
let alt_name = alt_name.to_cstr();
unsafe {
Self::from_raw(BNCreateIntegerTypeBuilder(
width,
&mut is_signed,
alt_name.as_ref().as_ptr() as _,
))
}
}
/// Create a float [`TypeBuilder`] with the given width. Analogous to [`Type::float`].
pub fn float(width: usize) -> Self {
unsafe { Self::from_raw(BNCreateFloatTypeBuilder(width, c"".as_ptr())) }
}
/// Create a float [`TypeBuilder`] with the given width and alternative name. Analogous to [`Type::named_float`].
pub fn named_float(width: usize, alt_name: &str) -> Self {
let alt_name = alt_name.to_cstr();
unsafe { Self::from_raw(BNCreateFloatTypeBuilder(width, alt_name.as_ptr())) }
}
/// Create an array [`TypeBuilder`] with the given element type and count. Analogous to [`Type::array`].
pub fn array<'a, T: Into<Conf<&'a Type>>>(ty: T, count: u64) -> Self {
let owned_raw_ty = Conf::<&Type>::into_raw(ty.into());
unsafe { Self::from_raw(BNCreateArrayTypeBuilder(&owned_raw_ty, count)) }
}
/// Create an enumeration [`TypeBuilder`] with the given width and signedness. Analogous to [`Type::enumeration`].
///
/// ## NOTE
///
/// The C/C++ APIs require an associated architecture, but in the core we only query the default_int_size if the given width is 0.
///
/// For simplicity's sake, that convention isn't followed, and you can query [`Architecture::default_integer_size`] if you need to.
pub fn enumeration<T: Into<Conf<bool>>>(
enumeration: &Enumeration,
width: NonZeroUsize,
is_signed: T,
) -> Self {
unsafe {
Self::from_raw(BNCreateEnumerationTypeBuilder(
// TODO: We pass nullptr arch, really we should not even be passing arch.
std::ptr::null_mut(),
enumeration.handle,
width.get(),
&mut is_signed.into().into(),
))
}
}
/// Create a structure [`TypeBuilder`]. Analogous to [`Type::structure`].
pub fn structure(structure_type: &Structure) -> Self {
unsafe { Self::from_raw(BNCreateStructureTypeBuilder(structure_type.handle)) }
}
/// Create a named type reference [`TypeBuilder`]. Analogous to [`Type::named_type`].
pub fn named_type(type_reference: &NamedTypeReference) -> Self {
let mut is_const = Conf::new(false, MIN_CONFIDENCE).into();
let mut is_volatile = Conf::new(false, MIN_CONFIDENCE).into();
unsafe {
Self::from_raw(BNCreateNamedTypeReferenceBuilder(
type_reference.handle,
0,
1,
&mut is_const,
&mut is_volatile,
))
}
}
/// Create a named type reference [`TypeBuilder`] from a type and name. Analogous to [`Type::named_type_from_type`].
pub fn named_type_from_type<T: Into<QualifiedName>>(name: T, t: &Type) -> Self {
let mut raw_name = QualifiedName::into_raw(name.into());
let id = c"";
let result = unsafe {
Self::from_raw(BNCreateNamedTypeReferenceBuilderFromTypeAndId(
id.as_ptr() as *mut _,
&mut raw_name,
t.handle,
))
};
QualifiedName::free_raw(raw_name);
result
}
// TODO: Deprecate this for a FunctionBuilder (along with the Type variant?)
/// NOTE: This is likely to be deprecated and removed in favor of a function type builder, please
/// use [`Type::function`] where possible.
pub fn function<'a, T: Into<ReturnValue>>(
return_value: T,
parameters: Vec<FunctionParameter>,
variable_arguments: bool,
) -> Self {
let mut owned_raw_return_value = ReturnValue::into_rust_raw(return_value.into());
let mut variable_arguments = Conf::new(variable_arguments, MAX_CONFIDENCE).into();
let mut can_return = Conf::new(true, MIN_CONFIDENCE).into();
let mut pure = Conf::new(false, MIN_CONFIDENCE).into();
let mut raw_calling_convention: BNCallingConventionWithConfidence =
BNCallingConventionWithConfidence {
convention: std::ptr::null_mut(),
confidence: MIN_CONFIDENCE,
};
let mut stack_adjust = Conf::new(0, MIN_CONFIDENCE).into();
let mut raw_parameters = parameters
.into_iter()
.map(FunctionParameter::into_raw)
.collect::<Vec<_>>();
let reg_stack_adjust_regs = std::ptr::null_mut();
let reg_stack_adjust_values = std::ptr::null_mut();
let result = unsafe {
Self::from_raw(BNCreateFunctionTypeBuilder(
&mut owned_raw_return_value,
&mut raw_calling_convention,
raw_parameters.as_mut_ptr(),
raw_parameters.len(),
&mut variable_arguments,
&mut can_return,
&mut stack_adjust,
reg_stack_adjust_regs,
reg_stack_adjust_values,
0,
BNNameType::NoNameType,
&mut pure,
))
};
for raw_param in raw_parameters {
FunctionParameter::free_raw(raw_param);
}
result
}
// TODO: Deprecate this for a FunctionBuilder (along with the Type variant?)
/// NOTE: This is likely to be deprecated and removed in favor of a function type builder, please
/// use [`Type::function_with_opts`] where possible.
pub fn function_with_opts<
'a,
T: Into<ReturnValue>,
C: Into<Conf<Ref<CoreCallingConvention>>>,
>(
return_value: T,
parameters: &[FunctionParameter],
variable_arguments: bool,
calling_convention: C,
stack_adjust: Conf<i64>,
) -> Self {
let mut owned_raw_return_value = ReturnValue::into_rust_raw(return_value.into());
let mut variable_arguments = Conf::new(variable_arguments, MAX_CONFIDENCE).into();
let mut can_return = Conf::new(true, MIN_CONFIDENCE).into();
let mut pure = Conf::new(false, MIN_CONFIDENCE).into();
let mut owned_raw_calling_convention =
Conf::<Ref<CoreCallingConvention>>::into_owned_raw(&calling_convention.into());
let mut stack_adjust = stack_adjust.into();
let mut raw_parameters = parameters
.iter()
.cloned()
.map(FunctionParameter::into_raw)
.collect::<Vec<_>>();
// TODO: Update type signature and include these (will be a breaking change)
let reg_stack_adjust_regs = std::ptr::null_mut();
let reg_stack_adjust_values = std::ptr::null_mut();
let result = unsafe {
Self::from_raw(BNCreateFunctionTypeBuilder(
&mut owned_raw_return_value,
&mut owned_raw_calling_convention,
raw_parameters.as_mut_ptr(),
raw_parameters.len(),
&mut variable_arguments,
&mut can_return,
&mut stack_adjust,
reg_stack_adjust_regs,
reg_stack_adjust_values,
0,
BNNameType::NoNameType,
&mut pure,
))
};
for raw_param in raw_parameters {
FunctionParameter::free_raw(raw_param);
}
result
}
/// Create a pointer [`TypeBuilder`] with the given target type. Analogous to [`Type::pointer`].
pub fn pointer<'a, A: Architecture, T: Into<Conf<&'a Type>>>(arch: &A, ty: T) -> Self {
Self::pointer_with_options(arch, ty, false, false, None)
}
/// Create a const pointer [`TypeBuilder`] with the given target type. Analogous to [`Type::const_pointer`].
pub fn const_pointer<'a, A: Architecture, T: Into<Conf<&'a Type>>>(arch: &A, ty: T) -> Self {
Self::pointer_with_options(arch, ty, true, false, None)
}
pub fn pointer_with_options<'a, A: Architecture, T: Into<Conf<&'a Type>>>(
arch: &A,
ty: T,
is_const: bool,
is_volatile: bool,
ref_type: Option<ReferenceType>,
) -> Self {
let arch_ptr_size = arch.address_size();
Self::pointer_of_width(ty, arch_ptr_size, is_const, is_volatile, ref_type)
}
pub fn pointer_of_width<'a, T: Into<Conf<&'a Type>>>(
ty: T,
size: usize,
is_const: bool,
is_volatile: bool,
ref_type: Option<ReferenceType>,
) -> Self {
let mut is_const = Conf::new(is_const, MAX_CONFIDENCE).into();
let mut is_volatile = Conf::new(is_volatile, MAX_CONFIDENCE).into();
let owned_raw_ty = Conf::<&Type>::into_raw(ty.into());
unsafe {
Self::from_raw(BNCreatePointerTypeBuilderOfWidth(
size,
&owned_raw_ty,
&mut is_const,
&mut is_volatile,
ref_type.unwrap_or(ReferenceType::PointerReferenceType),
))
}
}
}
impl Display for TypeBuilder {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", unsafe {
BnString::into_string(BNGetTypeBuilderString(self.handle, std::ptr::null_mut()))
})
}
}
impl Drop for TypeBuilder {
fn drop(&mut self) {
unsafe { BNFreeTypeBuilder(self.handle) };
}
}
/// The core model for types in Binary Ninja.
///
/// A [`Type`] is how we model the storage of a [`Variable`] or [`crate::variable::DataVariable`] as
/// well as propagate information such as the constness of a variable. Types are also used to declare
/// function signatures, such as the [`FunctionParameter`]'s and return type.
///
/// Types are immutable. To change a type, you must create a new one either using [`TypeBuilder`] or
/// one of the helper functions:
///
/// - [`Type::void`]
/// - [`Type::bool`]
/// - [`Type::char`]
/// - [`Type::wide_char`]
/// - [`Type::int`], [`Type::named_int`]
/// - [`Type::float`], [`Type::named_float`]
/// - [`Type::array`]
/// - [`Type::enumeration`]
/// - [`Type::structure`]
/// - [`Type::named_type`], [`Type::named_type_from_type`]
/// - [`Type::function`], [`Type::function_with_opts`]
/// - [`Type::pointer`], [`Type::const_pointer`], [`Type::pointer_of_width`], [`Type::pointer_with_options`]
///
/// # Example
///
/// As an example, defining a _named_ type within a [`BinaryView`]:
///
/// ```no_run
/// # use binaryninja::types::Type;
/// let bv = binaryninja::load("example.bin").unwrap();
/// 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);
/// ```
#[repr(transparent)]
pub struct Type {
pub handle: *mut BNType,
}
impl Type {
pub unsafe fn from_raw(handle: *mut BNType) -> Self {
debug_assert!(!handle.is_null());
Self { handle }
}
pub unsafe fn ref_from_raw(handle: *mut BNType) -> Ref<Self> {
debug_assert!(!handle.is_null());
Ref::new(Self { handle })
}
pub fn to_builder(&self) -> TypeBuilder {
TypeBuilder::new(self)
}
pub fn type_class(&self) -> TypeClass {
unsafe { BNGetTypeClass(self.handle) }
}
// TODO: We need to decide on a public type to represent type width.
// TODO: The api uses both `u64` and `usize`, pick one or a new type!
/// The size of the type in bytes.
pub fn width(&self) -> u64 {
unsafe { BNGetTypeWidth(self.handle) }
}
pub fn alignment(&self) -> usize {
unsafe { BNGetTypeAlignment(self.handle) }
}
pub fn is_signed(&self) -> Conf<bool> {
unsafe { BNIsTypeSigned(self.handle).into() }
}
pub fn integer_display_type(&self) -> IntegerDisplayType {
unsafe { BNGetIntegerTypeDisplayType(self.handle) }
}
pub fn is_const(&self) -> Conf<bool> {
unsafe { BNIsTypeConst(self.handle).into() }
}
pub fn is_volatile(&self) -> Conf<bool> {
unsafe { BNIsTypeVolatile(self.handle).into() }
}
pub fn is_floating_point(&self) -> bool {
unsafe { BNIsTypeFloatingPoint(self.handle) }
}
pub fn child_type(&self) -> Option<Conf<Ref<Type>>> {
let raw_target = unsafe { BNGetChildType(self.handle) };
match raw_target.type_.is_null() {
false => Some(Conf::<Ref<Type>>::from_owned_raw(raw_target)),
true => None,
}
}
/// This is an alias for [`Self::child_type`].
pub fn target(&self) -> Option<Conf<Ref<Type>>> {
self.child_type()
}
/// This is an alias for [`Self::child_type`].
pub fn element_type(&self) -> Option<Conf<Ref<Type>>> {
self.child_type()
}
/// This is an alias for [`Self::child_type`].
pub fn return_value(&self) -> Option<Conf<Ref<Type>>> {
self.child_type()
}
pub fn calling_convention(&self) -> Option<Conf<Ref<CoreCallingConvention>>> {
let convention_confidence = unsafe { BNGetTypeCallingConvention(self.handle) };
match convention_confidence.convention.is_null() {
false => Some(Conf::<Ref<CoreCallingConvention>>::from_owned_raw(
convention_confidence,
)),
true => None,
}
}
pub fn parameters(&self) -> Option<Vec<FunctionParameter>> {
unsafe {
let mut count = 0;
let raw_parameters_ptr = BNGetTypeParameters(self.handle, &mut count);
match raw_parameters_ptr.is_null() {
false => {
let raw_parameters = std::slice::from_raw_parts(raw_parameters_ptr, count);
let parameters = raw_parameters
.iter()
.map(FunctionParameter::from_raw)
.collect();
BNFreeTypeParameterList(raw_parameters_ptr, count);
Some(parameters)
}
true => None,
}
}
}
pub fn has_variable_arguments(&self) -> Conf<bool> {
unsafe { BNTypeHasVariableArguments(self.handle).into() }
}
pub fn can_return(&self) -> Conf<bool> {
unsafe { BNFunctionTypeCanReturn(self.handle).into() }
}
pub fn pure(&self) -> Conf<bool> {
unsafe { BNIsTypePure(self.handle).into() }
}
// TODO: This naming is problematic... rename to `as_structure`?
// TODO: We wouldn't need these sort of functions if we destructured `Type`...
pub fn get_structure(&self) -> Option<Ref<Structure>> {
let raw_struct_ptr = unsafe { BNGetTypeStructure(self.handle) };
match raw_struct_ptr.is_null() {
false => Some(unsafe { Structure::ref_from_raw(raw_struct_ptr) }),
true => None,
}
}
// TODO: This naming is problematic... rename to `as_enumeration`?
// TODO: We wouldn't need these sort of functions if we destructured `Type`...
pub fn get_enumeration(&self) -> Option<Ref<Enumeration>> {
let raw_enum_ptr = unsafe { BNGetTypeEnumeration(self.handle) };
match raw_enum_ptr.is_null() {
false => Some(unsafe { Enumeration::ref_from_raw(raw_enum_ptr) }),
true => None,
}
}
// TODO: This naming is problematic... rename to `as_named_type_reference`?
// TODO: We wouldn't need these sort of functions if we destructured `Type`...
pub fn get_named_type_reference(&self) -> Option<Ref<NamedTypeReference>> {
let raw_type_ref_ptr = unsafe { BNGetTypeNamedTypeReference(self.handle) };
match raw_type_ref_ptr.is_null() {
false => Some(unsafe { NamedTypeReference::ref_from_raw(raw_type_ref_ptr) }),
true => None,
}
}
pub fn count(&self) -> u64 {
unsafe { BNGetTypeElementCount(self.handle) }
}
pub fn offset(&self) -> u64 {
unsafe { BNGetTypeOffset(self.handle) }
}
pub fn stack_adjustment(&self) -> Conf<i64> {
unsafe { BNGetTypeStackAdjustment(self.handle).into() }
}
pub fn registered_name(&self) -> Option<Ref<NamedTypeReference>> {
let raw_type_ref_ptr = unsafe { BNGetRegisteredTypeName(self.handle) };
match raw_type_ref_ptr.is_null() {
false => Some(unsafe { NamedTypeReference::ref_from_raw(raw_type_ref_ptr) }),
true => None,
}
}
pub fn pointer_base_type(&self) -> BNPointerBaseType {
unsafe { BNTypeGetPointerBaseType(self.handle) }
}
pub fn pointer_base_offset(&self) -> i64 {
unsafe { BNTypeGetPointerBaseOffset(self.handle) }
}
// TODO : This and properties
// pub fn tokens(&self) -> ? {}
pub fn void() -> Ref<Self> {
unsafe { Self::ref_from_raw(BNCreateVoidType()) }
}
pub fn bool() -> Ref<Self> {
unsafe { Self::ref_from_raw(BNCreateBoolType()) }
}
pub fn char() -> Ref<Self> {
Self::int(1, true)
}
pub fn wide_char(width: usize) -> Ref<Self> {
unsafe { Self::ref_from_raw(BNCreateWideCharType(width, c"".as_ptr())) }
}
pub fn int(width: usize, is_signed: bool) -> Ref<Self> {
let mut is_signed = Conf::new(is_signed, MAX_CONFIDENCE).into();
unsafe { Self::ref_from_raw(BNCreateIntegerType(width, &mut is_signed, c"".as_ptr())) }
}
pub fn named_int(width: usize, is_signed: bool, alt_name: &str) -> Ref<Self> {
let mut is_signed = Conf::new(is_signed, MAX_CONFIDENCE).into();
let alt_name = alt_name.to_cstr();
unsafe {
Self::ref_from_raw(BNCreateIntegerType(
width,
&mut is_signed,
alt_name.as_ptr(),
))
}
}
pub fn float(width: usize) -> Ref<Self> {
unsafe { Self::ref_from_raw(BNCreateFloatType(width, c"".as_ptr())) }
}
pub fn named_float(width: usize, alt_name: &str) -> Ref<Self> {
let alt_name = alt_name.to_cstr();
unsafe { Self::ref_from_raw(BNCreateFloatType(width, alt_name.as_ptr())) }
}
pub fn array<'a, T: Into<Conf<&'a Type>>>(ty: T, count: u64) -> Ref<Self> {
let owned_raw_ty = Conf::<&Type>::into_raw(ty.into());
unsafe { Self::ref_from_raw(BNCreateArrayType(&owned_raw_ty, count)) }
}
/// ## NOTE
///
/// The C/C++ APIs require an associated architecture, but in the core we only query the default_int_size if the given width is 0.
///
/// For simplicity's sake, that convention isn't followed, and you can query [`Architecture::default_integer_size`] if you need to.
pub fn enumeration<T: Into<Conf<bool>>>(
enumeration: &Enumeration,
width: NonZeroUsize,
is_signed: T,
) -> Ref<Self> {
unsafe {
Self::ref_from_raw(BNCreateEnumerationType(
// TODO: We pass nullptr arch, really we should not even be passing arch.
std::ptr::null_mut(),
enumeration.handle,
width.get(),
&mut is_signed.into().into(),
))
}
}
pub fn structure(structure: &Structure) -> Ref<Self> {
unsafe { Self::ref_from_raw(BNCreateStructureType(structure.handle)) }
}
pub fn named_type(type_reference: &NamedTypeReference) -> Ref<Self> {
let mut is_const = Conf::new(false, MIN_CONFIDENCE).into();
let mut is_volatile = Conf::new(false, MIN_CONFIDENCE).into();
unsafe {
Self::ref_from_raw(BNCreateNamedTypeReference(
type_reference.handle,
0,
1,
&mut is_const,
&mut is_volatile,
))
}
}
pub fn named_type_from_type<T: Into<QualifiedName>>(name: T, t: &Type) -> Ref<Self> {
let mut raw_name = QualifiedName::into_raw(name.into());
// TODO: No id is present for this call?
let id = c"";
let result = unsafe {
Self::ref_from_raw(BNCreateNamedTypeReferenceFromTypeAndId(
id.as_ptr(),
&mut raw_name,
t.handle,
))
};
QualifiedName::free_raw(raw_name);
result
}
// TODO: FunctionBuilder
pub fn function<'a, T: Into<ReturnValue>>(
return_value: T,
parameters: Vec<FunctionParameter>,
variable_arguments: bool,
) -> Ref<Self> {
let mut owned_raw_return_value = ReturnValue::into_rust_raw(return_value.into());
let mut variable_arguments = Conf::new(variable_arguments, MAX_CONFIDENCE).into();
let mut can_return = Conf::new(true, MIN_CONFIDENCE).into();
let mut pure = Conf::new(false, MIN_CONFIDENCE).into();
let mut raw_calling_convention: BNCallingConventionWithConfidence =
BNCallingConventionWithConfidence {
convention: std::ptr::null_mut(),
confidence: MIN_CONFIDENCE,
};
let mut stack_adjust = Conf::new(0, MIN_CONFIDENCE).into();
let mut raw_parameters = parameters
.into_iter()
.map(FunctionParameter::into_raw)
.collect::<Vec<_>>();
let reg_stack_adjust_regs = std::ptr::null_mut();
let reg_stack_adjust_values = std::ptr::null_mut();
let result = unsafe {
Self::ref_from_raw(BNCreateFunctionType(
&mut owned_raw_return_value,
&mut raw_calling_convention,
raw_parameters.as_mut_ptr(),
raw_parameters.len(),
&mut variable_arguments,
&mut can_return,
&mut stack_adjust,
reg_stack_adjust_regs,
reg_stack_adjust_values,
0,
BNNameType::NoNameType,
&mut pure,
))
};
ReturnValue::free_rust_raw(owned_raw_return_value);
for raw_param in raw_parameters {
FunctionParameter::free_raw(raw_param);
}
result
}
// TODO: FunctionBuilder
pub fn function_with_opts<
'a,
T: Into<ReturnValue>,
C: Into<Conf<Ref<CoreCallingConvention>>>,
>(
return_value: T,
parameters: &[FunctionParameter],
variable_arguments: bool,
calling_convention: C,
stack_adjust: Conf<i64>,
) -> Ref<Self> {
let mut owned_raw_return_value = ReturnValue::into_rust_raw(return_value.into());
let mut variable_arguments = Conf::new(variable_arguments, MAX_CONFIDENCE).into();
let mut can_return = Conf::new(true, MIN_CONFIDENCE).into();
let mut pure = Conf::new(false, MIN_CONFIDENCE).into();
let mut owned_raw_calling_convention =
Conf::<Ref<CoreCallingConvention>>::into_owned_raw(&calling_convention.into());
let mut stack_adjust = stack_adjust.into();
let mut raw_parameters = parameters
.iter()
.cloned()
.map(FunctionParameter::into_raw)
.collect::<Vec<_>>();
// TODO: Update type signature and include these (will be a breaking change)
let reg_stack_adjust_regs = std::ptr::null_mut();
let reg_stack_adjust_values = std::ptr::null_mut();
let result = unsafe {
Self::ref_from_raw(BNCreateFunctionType(
&mut owned_raw_return_value,
&mut owned_raw_calling_convention,
raw_parameters.as_mut_ptr(),
raw_parameters.len(),
&mut variable_arguments,
&mut can_return,
&mut stack_adjust,
reg_stack_adjust_regs,
reg_stack_adjust_values,
0,
BNNameType::NoNameType,
&mut pure,
))
};
ReturnValue::free_rust_raw(owned_raw_return_value);
for raw_param in raw_parameters {
FunctionParameter::free_raw(raw_param);
}
result
}
pub fn pointer<'a, A: Architecture, T: Into<Conf<&'a Type>>>(arch: &A, ty: T) -> Ref<Self> {
Self::pointer_with_options(arch, ty, false, false, None)
}
pub fn const_pointer<'a, A: Architecture, T: Into<Conf<&'a Type>>>(
arch: &A,
ty: T,
) -> Ref<Self> {
Self::pointer_with_options(arch, ty, true, false, None)
}
pub fn pointer_with_options<'a, A: Architecture, T: Into<Conf<&'a Type>>>(
arch: &A,
ty: T,
is_const: bool,
is_volatile: bool,
ref_type: Option<ReferenceType>,
) -> Ref<Self> {
let arch_pointer_size = arch.address_size();
Self::pointer_of_width(ty, arch_pointer_size, is_const, is_volatile, ref_type)
}
pub fn pointer_of_width<'a, T: Into<Conf<&'a Type>>>(
ty: T,
size: usize,
is_const: bool,
is_volatile: bool,
ref_type: Option<ReferenceType>,
) -> Ref<Self> {
let mut is_const = Conf::new(is_const, MAX_CONFIDENCE).into();
let mut is_volatile = Conf::new(is_volatile, MAX_CONFIDENCE).into();
let owned_raw_ty = Conf::<&Type>::into_raw(ty.into());
unsafe {
Self::ref_from_raw(BNCreatePointerTypeOfWidth(
size,
&owned_raw_ty,
&mut is_const,
&mut is_volatile,
ref_type.unwrap_or(ReferenceType::PointerReferenceType),
))
}
}
pub fn generate_auto_demangled_type_id<T: Into<QualifiedName>>(name: T) -> String {
let mut raw_name = QualifiedName::into_raw(name.into());
let type_id =
unsafe { BnString::into_string(BNGenerateAutoDemangledTypeId(&mut raw_name)) };
QualifiedName::free_raw(raw_name);
type_id
}
pub fn deref_named_type_reference(&self, view: &BinaryView) -> Ref<Type> {
unsafe { Self::ref_from_raw(BNDerefNamedTypeReference(view.handle, self.handle)) }
}
}
impl Display for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", unsafe {
BnString::into_string(BNGetTypeString(
self.handle,
std::ptr::null_mut(),
BNTokenEscapingType::NoTokenEscapingType,
))
})
}
}
impl Debug for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// You might be tempted to rip this atrocity out and make this more "sensible". READ BELOW!
// Type is a one-size fits all structure, these are actually its fields! If we wanted to
// omit some fields for different type classes, what you really want to do is implement your
// own formatter. This is supposed to represent the structure entirely, it's not supposed to be pretty!
f.debug_struct("Type")
.field("type_class", &self.type_class())
.field("width", &self.width())
.field("alignment", &self.alignment())
.field("is_signed", &self.is_signed())
.field("is_const", &self.is_const())
.field("is_volatile", &self.is_volatile())
.field("child_type", &self.child_type())
.field("calling_convention", &self.calling_convention())
.field("parameters", &self.parameters())
.field("has_variable_arguments", &self.has_variable_arguments())
.field("can_return", &self.can_return())
.field("pure", &self.pure())
.field("get_structure", &self.get_structure())
.field("get_enumeration", &self.get_enumeration())
.field("get_named_type_reference", &self.get_named_type_reference())
.field("count", &self.count())
.field("offset", &self.offset())
.field("stack_adjustment", &self.stack_adjustment())
.field("registered_name", &self.registered_name())
.finish()
}
}
impl PartialEq for Type {
fn eq(&self, other: &Self) -> bool {
unsafe { BNTypesEqual(self.handle, other.handle) }
}
}
impl Eq for Type {}
impl Hash for Type {
fn hash<H: Hasher>(&self, state: &mut H) {
self.handle.hash(state);
}
}
unsafe impl Send for Type {}
unsafe impl Sync for Type {}
unsafe impl RefCountable for Type {
unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
Self::ref_from_raw(BNNewTypeReference(handle.handle))
}
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) }
}
}
impl CoreArrayProvider for Type {
type Raw = *mut BNType;
type Context = ();
type Wrapped<'a> = &'a Self;
}
unsafe impl CoreArrayProviderInner for Type {
unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
BNFreeTypeList(raw, count)
}
unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
// TODO: This is assuming &'a Type is &*mut BNType
std::mem::transmute(raw)
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ValueLocationComponent {
pub variable: Variable,
pub offset: i64,
pub size: Option<u64>,
}
impl ValueLocationComponent {
pub(crate) fn from_raw(value: &BNValueLocationComponent) -> Self {
let variable = Variable::from(&value.variable);
let size = if value.sizeValid {
Some(value.size)
} else {
None
};
Self {
variable,
offset: value.offset,
size,
}
}
pub(crate) fn into_raw(value: &Self) -> BNValueLocationComponent {
BNValueLocationComponent {
variable: value.variable.into(),
offset: value.offset,
sizeValid: value.size.is_some(),
size: value.size.unwrap_or(0),
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ValueLocation {
pub components: Vec<ValueLocationComponent>,
pub indirect: bool,
pub returned_pointer: Option<Variable>,
}
impl ValueLocation {
pub fn from_variable(var: Variable) -> Self {
Self {
components: vec![ValueLocationComponent {
variable: var,
offset: 0,
size: None,
}],
indirect: false,
returned_pointer: None,
}
}
pub fn from_register(reg: impl Register) -> Self {
Self::from_variable(Variable::from_register(reg))
}
pub fn from_register_id(reg: RegisterId) -> Self {
Self::from_variable(Variable::from_register_id(reg))
}
pub fn from_stack_offset(offset: i64) -> Self {
Self::from_variable(Variable::from_stack_offset(offset))
}
pub fn is_valid(&self) -> bool {
!self.components.is_empty()
}
pub fn variable_for_return_value(&self) -> Option<Variable> {
let value_raw = Self::into_rust_raw(&self);
let mut var_raw = BNVariable::default();
let valid = unsafe { BNGetValueLocationVariableForReturnValue(&value_raw, &mut var_raw) };
Self::free_rust_raw(value_raw);
if valid {
Some(var_raw.into())
} else {
None
}
}
pub fn variable_for_parameter(&self, idx: usize) -> Option<Variable> {
let value_raw = Self::into_rust_raw(&self);
let mut var_raw = BNVariable::default();
let valid =
unsafe { BNGetValueLocationVariableForParameter(&value_raw, &mut var_raw, idx) };
Self::free_rust_raw(value_raw);
if valid {
Some(var_raw.into())
} else {
None
}
}
pub(crate) fn from_raw(loc: &BNValueLocation) -> Self {
let components_raw: &[BNValueLocationComponent] =
unsafe { crate::ffi::slice_from_raw_parts(loc.components, loc.count) };
Self {
components: components_raw
.iter()
.map(|component| ValueLocationComponent::from_raw(component))
.collect(),
indirect: loc.indirect,
returned_pointer: if loc.returnedPointerValid {
Some(Variable::from(&loc.returnedPointer))
} else {
None
},
}
}
pub fn into_rust_raw(value: &Self) -> BNValueLocation {
let components: Box<[BNValueLocationComponent]> = value
.components
.iter()
.map(|component| ValueLocationComponent::into_raw(component))
.collect();
BNValueLocation {
count: components.len(),
components: Box::leak(components).as_mut_ptr(),
indirect: value.indirect,
returnedPointerValid: value.returned_pointer.is_some(),
returnedPointer: if let Some(ptr) = value.returned_pointer {
ptr.into()
} else {
Variable::new(VariableSourceType::RegisterVariableSourceType, 0, 0).into()
},
}
}
/// Free a RUST ALLOCATED possible value set. Do not use this with CORE ALLOCATED values.
pub fn free_rust_raw(value: BNValueLocation) {
let raw_components =
unsafe { std::slice::from_raw_parts_mut(value.components, value.count) };
let _ = unsafe { Box::from_raw(raw_components) };
}
}
impl Into<ValueLocation> for Variable {
fn into(self) -> ValueLocation {
ValueLocation {
components: vec![ValueLocationComponent {
variable: self,
offset: 0,
size: None,
}],
indirect: false,
returned_pointer: None,
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ReturnValue {
pub ty: Conf<Ref<Type>>,
pub location: Option<Conf<ValueLocation>>,
}
impl ReturnValue {
pub(crate) fn from_raw(value: &BNReturnValue) -> Self {
Self {
ty: Conf::new(
unsafe { Type::from_raw(value.type_).to_owned() },
value.typeConfidence,
),
location: match value.defaultLocation {
false => Some(Conf::new(
ValueLocation::from_raw(&value.location),
value.locationConfidence,
)),
true => None,
},
}
}
/// Take ownership over an "owned" **core allocated** value. Do not call this for a rust allocated value.
pub(crate) fn from_owned_core_raw(mut value: BNReturnValue) -> Self {
let owned = Self::from_raw(&value);
Self::free_core_raw(&mut value);
owned
}
pub(crate) fn into_rust_raw(value: Self) -> BNReturnValue {
BNReturnValue {
type_: unsafe { Ref::into_raw(value.ty.contents) }.handle,
typeConfidence: value.ty.confidence,
defaultLocation: value.location.is_none(),
location: ValueLocation::into_rust_raw(
value
.location
.as_ref()
.map(|v| &v.contents)
.unwrap_or(&ValueLocation {
components: Vec::new(),
indirect: false,
returned_pointer: None,
}),
),
locationConfidence: value.location.as_ref().map(|v| v.confidence).unwrap_or(0),
}
}
/// Free a CORE ALLOCATED possible value set. Do not use this with [Self::into_rust_raw] values.
pub(crate) fn free_core_raw(value: &mut BNReturnValue) {
unsafe { BNFreeReturnValue(value) }
}
/// Free a RUST ALLOCATED possible value set. Do not use this with CORE ALLOCATED values.
pub(crate) fn free_rust_raw(value: BNReturnValue) {
let _ = unsafe { Type::ref_from_raw(value.type_) };
ValueLocation::free_rust_raw(value.location);
}
}
impl Into<ReturnValue> for Ref<Type> {
fn into(self) -> ReturnValue {
ReturnValue {
ty: self.into(),
location: None,
}
}
}
impl Into<ReturnValue> for &Ref<Type> {
fn into(self) -> ReturnValue {
ReturnValue {
ty: self.clone().into(),
location: None,
}
}
}
impl Into<ReturnValue> for &Type {
fn into(self) -> ReturnValue {
ReturnValue {
ty: self.to_owned().into(),
location: None,
}
}
}
impl Into<ReturnValue> for Conf<Ref<Type>> {
fn into(self) -> ReturnValue {
ReturnValue {
ty: self,
location: None,
}
}
}
impl Into<ReturnValue> for &Conf<Ref<Type>> {
fn into(self) -> ReturnValue {
ReturnValue {
ty: self.clone(),
location: None,
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum ValueLocationSource {
Default,
PassByValue,
PassByReference,
Custom(ValueLocation),
}
impl From<Option<ValueLocation>> for ValueLocationSource {
fn from(loc: Option<ValueLocation>) -> Self {
match loc {
Some(loc) => ValueLocationSource::Custom(loc),
None => ValueLocationSource::Default,
}
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct FunctionParameter {
pub ty: Conf<Ref<Type>>,
pub name: String,
pub location: ValueLocationSource,
}
impl FunctionParameter {
pub(crate) fn from_raw(value: &BNFunctionParameter) -> Self {
// TODO: I copied this from the original `from_raw` function.
// TODO: So this actually needs to be audited later.
let name = if value.name.is_null() {
String::new()
} else {
raw_to_string(value.name as *const _).unwrap()
};
Self {
ty: Conf::new(
unsafe { Type::from_raw(value.type_).to_owned() },
value.typeConfidence,
),
name,
location: match value.locationSource {
BNValueLocationSource::DefaultLocationSource => ValueLocationSource::Default,
BNValueLocationSource::PassByValueLocationSource => {
ValueLocationSource::PassByValue
}
BNValueLocationSource::PassByReferenceLocationSource => {
ValueLocationSource::PassByReference
}
BNValueLocationSource::CustomLocationSource => {
ValueLocationSource::Custom(ValueLocation::from_raw(&value.location))
}
},
}
}
#[allow(unused)]
pub(crate) fn from_owned_raw(value: BNFunctionParameter) -> Self {
let owned = Self::from_raw(&value);
Self::free_raw(value);
owned
}
pub(crate) fn into_raw(value: Self) -> BNFunctionParameter {
let bn_name = BnString::new(value.name);
BNFunctionParameter {
name: BnString::into_raw(bn_name),
type_: unsafe { Ref::into_raw(value.ty.contents) }.handle,
typeConfidence: value.ty.confidence,
locationSource: match value.location {
ValueLocationSource::Default => BNValueLocationSource::DefaultLocationSource,
ValueLocationSource::PassByValue => {
BNValueLocationSource::PassByValueLocationSource
}
ValueLocationSource::PassByReference => {
BNValueLocationSource::PassByReferenceLocationSource
}
ValueLocationSource::Custom(_) => BNValueLocationSource::CustomLocationSource,
},
location: match &value.location {
ValueLocationSource::Custom(loc) => ValueLocation::into_rust_raw(loc),
_ => ValueLocation::into_rust_raw(&ValueLocation {
components: Vec::new(),
indirect: false,
returned_pointer: None,
}),
},
}
}
pub(crate) fn free_raw(value: BNFunctionParameter) {
unsafe { BnString::free_raw(value.name) };
let _ = unsafe { Type::ref_from_raw(value.type_) };
ValueLocation::free_rust_raw(value.location);
}
pub fn new<T: Into<Conf<Ref<Type>>>>(
ty: T,
name: String,
location: impl Into<ValueLocationSource>,
) -> Self {
Self {
ty: ty.into(),
name,
location: location.into(),
}
}
}
#[derive(PartialEq, Eq, Hash)]
pub struct NamedTypeReference {
pub(crate) handle: *mut BNNamedTypeReference,
}
impl NamedTypeReference {
pub(crate) unsafe fn from_raw(handle: *mut BNNamedTypeReference) -> Self {
debug_assert!(!handle.is_null());
Self { handle }
}
pub(crate) unsafe fn ref_from_raw(handle: *mut BNNamedTypeReference) -> Ref<Self> {
debug_assert!(!handle.is_null());
Ref::new(Self { handle })
}
/// Create an NTR to a type that did not come directly from a BinaryView's types list.
/// That is to say, if you're referencing a new type you're GOING to add, use this.
/// You should not assign type ids yourself, that is the responsibility of the BinaryView
/// implementation after your types have been added. Just make sure the names match up and
/// the core will do the id stuff for you.
pub fn new<T: Into<QualifiedName>>(type_class: NamedTypeReferenceClass, name: T) -> Ref<Self> {
let mut raw_name = QualifiedName::into_raw(name.into());
let result = unsafe {
Self::ref_from_raw(BNCreateNamedType(
type_class,
std::ptr::null(),
&mut raw_name,
))
};
QualifiedName::free_raw(raw_name);
result
}
/// Create an NTR to a type with an existing type id, which generally means it came directly
/// from a BinaryView's types list and its id was looked up using `BinaryView::get_type_id`.
/// You should not assign type ids yourself: if you use this to reference a type you are going
/// to create but have not yet created, you may run into problems when giving your types to
/// a BinaryView.
pub fn new_with_id<T: Into<QualifiedName>>(
type_class: NamedTypeReferenceClass,
type_id: &str,
name: T,
) -> Ref<Self> {
let type_id = type_id.to_cstr();
let mut raw_name = QualifiedName::into_raw(name.into());
let result = unsafe {
Self::ref_from_raw(BNCreateNamedType(
type_class,
type_id.as_ref().as_ptr() as _,
&mut raw_name,
))
};
QualifiedName::free_raw(raw_name);
result
}
pub fn name(&self) -> QualifiedName {
let raw_name = unsafe { BNGetTypeReferenceName(self.handle) };
QualifiedName::from_owned_raw(raw_name)
}
pub fn id(&self) -> String {
unsafe { BnString::into_string(BNGetTypeReferenceId(self.handle)) }
}
pub fn class(&self) -> NamedTypeReferenceClass {
unsafe { BNGetTypeReferenceClass(self.handle) }
}
fn target_helper(&self, bv: &BinaryView, visited: &mut HashSet<String>) -> Option<Ref<Type>> {
let ty = bv.type_by_id(&self.id())?;
match ty.type_class() {
TypeClass::NamedTypeReferenceClass => {
// Recurse into the NTR type until we get the target type.
let ntr = ty
.get_named_type_reference()
.expect("NTR type class should always have a valid NTR");
match visited.insert(ntr.id()) {
true => ntr.target_helper(bv, visited),
// Cyclic reference, return None.
false => None,
}
}
// Found target type
_ => Some(ty),
}
}
/// Type referenced by this [`NamedTypeReference`].
///
/// Will return `None` if the reference is cyclic, or the target type does not exist.
pub fn target(&self, bv: &BinaryView) -> Option<Ref<Type>> {
self.target_helper(bv, &mut HashSet::new())
}
}
impl ToOwned for NamedTypeReference {
type Owned = Ref<Self>;
fn to_owned(&self) -> Self::Owned {
unsafe { RefCountable::inc_ref(self) }
}
}
unsafe impl RefCountable for NamedTypeReference {
unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
Self::ref_from_raw(BNNewNamedTypeReference(handle.handle))
}
unsafe fn dec_ref(handle: &Self) {
BNFreeNamedTypeReference(handle.handle)
}
}
impl Debug for NamedTypeReference {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{} (id: {})", self.name(), self.id())
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct QualifiedNameAndType {
pub name: QualifiedName,
pub ty: Ref<Type>,
}
impl QualifiedNameAndType {
pub(crate) fn from_raw(value: &BNQualifiedNameAndType) -> Self {
Self {
name: QualifiedName::from_raw(&value.name),
ty: unsafe { Type::from_raw(value.type_).to_owned() },
}
}
pub(crate) fn from_owned_raw(value: BNQualifiedNameAndType) -> Self {
let owned = Self::from_raw(&value);
Self::free_raw(value);
owned
}
pub(crate) fn into_raw(value: Self) -> BNQualifiedNameAndType {
BNQualifiedNameAndType {
name: QualifiedName::into_raw(value.name),
type_: unsafe { Ref::into_raw(value.ty).handle },
}
}
pub(crate) fn free_raw(value: BNQualifiedNameAndType) {
QualifiedName::free_raw(value.name);
let _ = unsafe { Type::ref_from_raw(value.type_) };
}
pub fn new(name: QualifiedName, ty: Ref<Type>) -> Self {
Self { name, ty }
}
}
impl<T> From<(T, Ref<Type>)> for QualifiedNameAndType
where
T: Into<QualifiedName>,
{
fn from(value: (T, Ref<Type>)) -> Self {
Self {
name: value.0.into(),
ty: value.1,
}
}
}
impl<T> From<(T, &Type)> for QualifiedNameAndType
where
T: Into<QualifiedName>,
{
fn from(value: (T, &Type)) -> Self {
let ty = value.1.to_owned();
Self {
name: value.0.into(),
ty,
}
}
}
impl CoreArrayProvider for QualifiedNameAndType {
type Raw = BNQualifiedNameAndType;
type Context = ();
type Wrapped<'a> = Self;
}
unsafe impl CoreArrayProviderInner for QualifiedNameAndType {
unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
BNFreeTypeAndNameList(raw, count);
}
unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
QualifiedNameAndType::from_raw(raw)
}
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct QualifiedNameTypeAndId {
pub name: QualifiedName,
pub ty: Ref<Type>,
pub id: String,
}
impl QualifiedNameTypeAndId {
pub(crate) fn from_raw(value: &BNQualifiedNameTypeAndId) -> Self {
Self {
name: QualifiedName::from_raw(&value.name),
ty: unsafe { Type::from_raw(value.type_) }.to_owned(),
id: raw_to_string(value.id).unwrap(),
}
}
#[allow(unused)]
pub(crate) fn from_owned_raw(value: BNQualifiedNameTypeAndId) -> Self {
let owned = Self::from_raw(&value);
Self::free_raw(value);
owned
}
pub(crate) fn into_raw(value: Self) -> BNQualifiedNameTypeAndId {
let bn_id = BnString::new(value.id);
BNQualifiedNameTypeAndId {
name: QualifiedName::into_raw(value.name),
id: BnString::into_raw(bn_id),
type_: unsafe { Ref::into_raw(value.ty) }.handle,
}
}
pub(crate) fn free_raw(value: BNQualifiedNameTypeAndId) {
QualifiedName::free_raw(value.name);
let _ = unsafe { Type::ref_from_raw(value.type_) };
let _ = unsafe { BnString::from_raw(value.id) };
}
}
impl CoreArrayProvider for QualifiedNameTypeAndId {
type Raw = BNQualifiedNameTypeAndId;
type Context = ();
type Wrapped<'a> = QualifiedNameTypeAndId;
}
unsafe impl CoreArrayProviderInner for QualifiedNameTypeAndId {
unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
BNFreeTypeIdList(raw, count);
}
unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
QualifiedNameTypeAndId::from_raw(raw)
}
}
// TODO: Document how this type is used for many different purposes. (this is literally (string, type))
// TODO: Ex. the name might be the parser it came from
// TODO: Ex. the name might be the param name for an intrinsic input
// TODO: Should we make new types for each varying use case?
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct NameAndType {
pub name: String,
pub ty: Conf<Ref<Type>>,
}
impl NameAndType {
pub(crate) fn from_raw(value: &BNNameAndType) -> Self {
Self {
// TODO: I dislike using this function here.
name: raw_to_string(value.name as *mut _).unwrap(),
ty: Conf::new(
unsafe { Type::from_raw(value.type_).to_owned() },
value.typeConfidence,
),
}
}
#[allow(unused)]
pub(crate) fn from_owned_raw(value: BNNameAndType) -> Self {
let owned = Self::from_raw(&value);
Self::free_raw(value);
owned
}
pub(crate) fn into_raw(value: Self) -> BNNameAndType {
let bn_name = BnString::new(value.name);
BNNameAndType {
name: BnString::into_raw(bn_name),
type_: unsafe { Ref::into_raw(value.ty.contents) }.handle,
typeConfidence: value.ty.confidence,
}
}
pub(crate) fn free_raw(value: BNNameAndType) {
unsafe { BnString::free_raw(value.name) };
let _ = unsafe { Type::ref_from_raw(value.type_) };
}
pub fn new(name: impl Into<String>, ty: Conf<Ref<Type>>) -> Self {
Self {
name: name.into(),
ty,
}
}
}
impl CoreArrayProvider for NameAndType {
type Raw = BNNameAndType;
type Context = ();
type Wrapped<'a> = Self;
}
unsafe impl CoreArrayProviderInner for NameAndType {
unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
BNFreeNameAndTypeList(raw, count);
}
unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, _context: &'a Self::Context) -> Self::Wrapped<'a> {
NameAndType::from_raw(raw)
}
}
|