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
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
use super::attributes;
use crate::call_stack::MemoryAccess;
use crate::registers::Registers;
use std::convert::TryInto;
use gimli::{DwAte, Location, Piece, Reader};
use anyhow::{anyhow, Result};
use log::{debug, error, info};
use std::fmt;
/// A wrapper for `gimli::Piece` which also contains a boolean that describes if this piece has
/// already been used to evaluate a value.
/// This means that the offset in the type information should be used.
#[derive(Debug, Clone)]
struct MyPiece<R: Reader<Offset = usize>> {
/// The piece which contains location information.
pub piece: Piece<R>,
/// Is true if this piece has already been used to evaluate a value.
pub used_before: bool,
}
impl<R: Reader<Offset = usize>> MyPiece<R> {
/// Creates a new `MyPiece`.
pub fn new(piece: Piece<R>) -> MyPiece<R> {
MyPiece {
piece,
used_before: false,
}
}
/// Updates the size in_bits value and return a boolean which tells if the piece is consumed
/// and should be removed.
///
/// Description:
///
/// * `bit_size` - How many bits of data needed from the piece.
pub fn should_remove(&mut self, bit_size: u64) -> bool {
match self.piece.size_in_bits {
Some(val) => {
if val > bit_size {
self.piece.size_in_bits = Some(val - bit_size);
self.used_before = true;
false
} else {
self.used_before = true;
self.piece.size_in_bits = Some(0);
true
}
}
None => {
self.used_before = true;
false
}
}
}
}
/// Describes all the different Rust types values in the form of a tree structure.
#[derive(Debug, Clone)]
pub enum EvaluatorValue<R: Reader<Offset = usize>> {
/// A base_type type and value with location information.
Value(BaseTypeValue, ValueInformation),
/// A pointer_type type and value.
PointerTypeValue(Box<PointerTypeValue<R>>),
/// A variant type and value.
VariantValue(Box<VariantValue<R>>),
/// A variant_part type and value.
VariantPartValue(Box<VariantPartValue<R>>),
/// A subrange_type type and value.
SubrangeTypeValue(SubrangeTypeValue),
/// gimli-rs bytes value.
Bytes(R),
/// A array type value.
Array(Box<ArrayTypeValue<R>>),
/// A struct type value.
Struct(Box<StructureTypeValue<R>>),
/// A enum type value.
Enum(Box<EnumerationTypeValue<R>>),
/// A union type value.
Union(Box<UnionTypeValue<R>>),
/// A attribute type value.
Member(Box<MemberValue<R>>),
/// The value is optimized away.
OptimizedOut, // NOTE: Value is optimized out.
/// The variable has no location currently but had or will have one. Note that the location can
/// be a constant stored in the DWARF stack.
LocationOutOfRange,
/// The value is size 0 bits.
ZeroSize,
}
impl<R: Reader<Offset = usize>> fmt::Display for EvaluatorValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
EvaluatorValue::Value(val, _) => val.fmt(f),
EvaluatorValue::PointerTypeValue(pt) => pt.fmt(f),
EvaluatorValue::VariantValue(var) => var.fmt(f),
EvaluatorValue::VariantPartValue(vpa) => vpa.fmt(f),
EvaluatorValue::SubrangeTypeValue(srt) => srt.fmt(f),
EvaluatorValue::Bytes(byt) => write!(f, "{:?}", byt),
EvaluatorValue::Array(arr) => arr.fmt(f),
EvaluatorValue::Struct(stu) => stu.fmt(f),
EvaluatorValue::Enum(enu) => enu.fmt(f),
EvaluatorValue::Union(uni) => uni.fmt(f),
EvaluatorValue::Member(mem) => mem.fmt(f),
EvaluatorValue::OptimizedOut => write!(f, "< OptimizedOut >"),
EvaluatorValue::LocationOutOfRange => write!(f, "< LocationOutOfRange >"),
EvaluatorValue::ZeroSize => write!(f, "< ZeroSize >"),
}
}
}
impl<R: Reader<Offset = usize>> EvaluatorValue<R> {
/// Will return this value as a `BaseTypeValue` struct if possible.
pub fn to_value(self) -> Option<BaseTypeValue> {
match self {
EvaluatorValue::Value(val, _) => Some(val),
EvaluatorValue::Member(val) => val.value.to_value(),
EvaluatorValue::OptimizedOut => None,
EvaluatorValue::ZeroSize => None,
_ => None, // TODO: Find a better solution then this.
}
}
/// Will return the type of this value as a `String`.
pub fn get_type(&self) -> String {
match self {
// TODO Update
EvaluatorValue::Value(val, _) => val.get_type(),
EvaluatorValue::Array(arr) => arr.get_type(),
EvaluatorValue::Struct(stu) => stu.get_type(),
EvaluatorValue::Enum(enu) => enu.get_type(),
EvaluatorValue::Union(uni) => uni.get_type(),
EvaluatorValue::Member(mem) => mem.get_type(),
_ => "<unknown>".to_owned(),
}
}
/// Will return a `Vec` of location and unparsed value infromation about the value.
pub fn get_variable_information(self) -> Vec<ValueInformation> {
match self {
EvaluatorValue::Value(_, var_info) => vec![var_info],
EvaluatorValue::Array(arr) => {
let mut info = vec![];
for val in arr.values {
info.append(&mut val.get_variable_information());
}
info
}
EvaluatorValue::Struct(st) => {
let mut info = vec![];
for val in st.members {
info.append(&mut val.get_variable_information());
}
info
}
EvaluatorValue::Enum(en) => en.variant.get_variable_information(),
EvaluatorValue::Union(un) => {
let mut info = vec![];
for val in un.members {
info.append(&mut val.get_variable_information());
}
info
}
EvaluatorValue::Member(me) => me.value.get_variable_information(),
EvaluatorValue::OptimizedOut => {
vec![ValueInformation::new(
None,
vec![ValuePiece::Dwarf { value: None }],
)]
}
_ => vec![],
}
}
/// Evaluate a list of `Piece`s into a value and parse it to the given type.
///
/// Description:
///
/// * `dwarf` - A reference to gimli-rs `Dwarf` struct.
/// * `registers` - A register struct for accessing the register values.
/// * `mem` - A struct for accessing the memory of the debug target.
/// * `pieces` - A list of gimli-rs pieces containing the location information..
/// * `unit_offset` - A offset to the `Unit` which contains the given type DIE.
/// * `die_offset` - A offset to the DIE that contains the type of the value.
///
/// This function will use the location information in the `pieces` parameter to read the
/// values and parse it to the given type.
pub fn evaluate_variable_with_type<M: MemoryAccess>(
dwarf: &gimli::Dwarf<R>,
registers: &Registers,
mem: &mut M,
pieces: &[Piece<R>],
unit_offset: gimli::UnitSectionOffset,
die_offset: gimli::UnitOffset,
) -> Result<EvaluatorValue<R>> {
log::info!("evaluate_variable_with_type");
// Initialize the memory offset to 0.
let data_offset: u64 = 0;
// Get the unit of the current state.
let unit = match unit_offset {
gimli::UnitSectionOffset::DebugInfoOffset(offset) => {
let header = dwarf.debug_info.header_from_offset(offset)?;
dwarf.unit(header)?
}
gimli::UnitSectionOffset::DebugTypesOffset(_offset) => {
let mut iter = dwarf.debug_types.units();
let mut result = None;
while let Some(header) = iter.next()? {
if header.offset() == unit_offset {
result = Some(dwarf.unit(header)?);
break;
}
}
match result {
Some(val) => val,
None => {
error!("Could not find unit from offset");
return Err(anyhow!("Could not find unit from offset"));
}
}
}
};
info!("Found unit");
// Get the die of the current state.
let die = &unit.entry(die_offset)?;
info!("Found die");
let mut my_pieces = pieces.iter().map(|p| MyPiece::new(p.clone())).collect();
info!("has pieces");
// Continue evaluating the value of the current state.
EvaluatorValue::eval_type(
registers,
mem,
dwarf,
&unit,
die,
data_offset,
&mut my_pieces,
)
}
/// This function will evaluate the given pieces into a unsigned 32 bit integer.
///
/// Description:
///
/// * `registers` - A register struct for accessing the register values.
/// * `mem` - A struct for accessing the memory of the debug target.
/// * `pieces` - A list of gimli-rs pieces containing the location information..
pub fn evaluate_variable<M: MemoryAccess>(
registers: &Registers,
mem: &mut M,
pieces: &[Piece<R>],
) -> Result<EvaluatorValue<R>> {
log::debug!("evaluate_variable");
let mut my_pieces = pieces.iter().map(|p| MyPiece::new(p.clone())).collect();
EvaluatorValue::handle_eval_piece(registers, mem, 4, 0, DwAte(1), &mut my_pieces)
}
/// Will maybe consume a number of pieces to evaluate a base type.
///
/// Description:
///
/// * `registers` - A register struct for accessing the register values.
/// * `mem` - A struct for accessing the memory of the debug target.
/// * `byte_size` - The size of the base type in bytes.
/// * `data_offset` - The memory address offset.
/// * `encoding` - The encoding of the base type.
/// * `pieces` - A list of pieces containing the location and size information.
fn handle_eval_piece<M: MemoryAccess>(
registers: &Registers,
mem: &mut M,
byte_size: u64,
data_offset: u64,
encoding: DwAte,
pieces: &mut Vec<MyPiece<R>>,
) -> Result<EvaluatorValue<R>> {
debug!("encoding: {:?}", encoding);
debug!("byte_size: {:?}", byte_size);
debug!("pieces: {:?}", pieces);
if pieces.is_empty() {
return Ok(EvaluatorValue::OptimizedOut);
}
let mut all_bytes = vec![];
let mut value_pieces = vec![];
while all_bytes.len() < byte_size.try_into()? {
if pieces.is_empty() {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
//return Ok(EvaluatorValue::OptimizedOut);
}
// Evaluate the bytes needed from one gimli::Piece.
match pieces[0].piece.clone().location {
Location::Empty => {
// Remove piece if whole object is used.
let bit_size = 8 * (byte_size - all_bytes.len() as u64);
if pieces[0].should_remove(bit_size) {
pieces.remove(0);
}
return Ok(EvaluatorValue::OptimizedOut);
}
Location::Register { ref register } => {
match registers.get_register_value(®ister.0) {
Some(val) => {
// TODO: Mask the important bits?
let mut bytes = vec![];
bytes.extend_from_slice(&val.to_le_bytes());
bytes = trim_piece_bytes(bytes, &pieces[0].piece, 4); // 4 because 32 bit registers
let bytes_len = bytes.len();
all_bytes.extend_from_slice(&bytes);
value_pieces.extend_from_slice(&[ValuePiece::Register {
register: register.0,
byte_size: bytes_len,
}]);
// Remove piece if whole object is used.
let bit_size = 8 * (bytes_len as u64);
if pieces[0].should_remove(bit_size) {
pieces.remove(0);
}
}
None => return Err(anyhow!("Requires reg")),
};
}
Location::Address { mut address } => {
// Check if `data_offset` should be used.
address += {
if pieces[0].used_before {
data_offset
} else {
0
}
};
let num_bytes = match pieces[0].piece.size_in_bits {
Some(val) => {
let max_num_bytes = (val + 8 - 1) / 8;
let needed_num_bytes = byte_size - all_bytes.len() as u64;
if max_num_bytes < needed_num_bytes {
max_num_bytes
} else {
needed_num_bytes
}
}
None => byte_size - all_bytes.len() as u64,
} as usize;
let bytes = match mem.get_address(&(address as u32), num_bytes) {
Some(val) => val,
None => {
error!(
"can not read address: {:x} num_bytes: {:?}, Return error",
address as u64, num_bytes
);
return Err(anyhow!(
"can not read address: {:x} num_bytes: {:?}, Return error",
address as u64,
num_bytes
));
}
};
all_bytes.extend_from_slice(&bytes);
value_pieces.extend_from_slice(&[ValuePiece::Memory {
address: address as u32,
byte_size: num_bytes,
}]);
// Remove piece if whole object is used.
let bit_size = 8 * num_bytes as u64;
if pieces[0].should_remove(bit_size) {
pieces.remove(0);
}
}
Location::Value { value } => {
// Remove piece if whole object is used.
let bit_size = 8 * (byte_size - all_bytes.len() as u64);
if pieces[0].should_remove(bit_size) {
pieces.remove(0);
}
let parsed_value = convert_from_gimli_value(value);
return match parsed_value {
BaseTypeValue::Generic(v) => {
let correct_value = match (encoding, byte_size) {
(DwAte(1), 4) => BaseTypeValue::Address32(v as u32),
//(DwAte(1), 4) => BaseTypeValue::Reg32(v as u32),
(DwAte(2), _) => BaseTypeValue::Bool(v != 0),
(DwAte(7), 1) => BaseTypeValue::U8(v as u8),
(DwAte(7), 2) => BaseTypeValue::U16(v as u16),
(DwAte(7), 4) => BaseTypeValue::U32(v as u32),
(DwAte(7), 8) => BaseTypeValue::U64(v as u64),
(DwAte(5), 1) => BaseTypeValue::I8(v as i8),
(DwAte(5), 2) => BaseTypeValue::I16(v as i16),
(DwAte(5), 4) => BaseTypeValue::I32(v as i32),
(DwAte(5), 8) => BaseTypeValue::I64(v as i64),
(DwAte(4), 4) => BaseTypeValue::F32(v as f32),
(DwAte(4), 8) => BaseTypeValue::F64(v as f64),
_ => BaseTypeValue::Generic(v),
};
//
Ok(EvaluatorValue::Value(
correct_value,
ValueInformation::new(
None,
vec![ValuePiece::Dwarf { value: Some(value) }],
),
))
}
_ => Ok(EvaluatorValue::Value(
parsed_value,
ValueInformation {
raw: None,
pieces: vec![ValuePiece::Dwarf { value: Some(value) }],
},
)),
};
}
Location::Bytes { mut value } => {
let mut bytes = vec![];
let mut loops = byte_size as usize - all_bytes.len();
if value.len() < loops {
loops = value.len();
}
for _i in 0..loops {
bytes.push(value.read_u8()?);
}
value_pieces.extend_from_slice(&[ValuePiece::Bytes {
bytes: bytes.clone(),
}]);
all_bytes.extend_from_slice(&bytes.into_boxed_slice());
// Remove piece if whole object is used.
let bit_size = 8 * (byte_size - all_bytes.len() as u64);
if pieces[0].should_remove(bit_size) {
pieces.remove(0);
}
//return Ok(EvaluatorValue::Bytes(value.clone()));
}
Location::ImplicitPointer {
value: _,
byte_offset: _,
} => {
error!("Unimplemented");
return Err(anyhow!("Unimplemented"));
}
}
}
while all_bytes.len() > byte_size as usize {
all_bytes.pop(); // NOTE: Removes extra bytes if value is from register and less the 4 byts
}
Ok(EvaluatorValue::Value(
BaseTypeValue::parse_base_type(all_bytes.clone(), encoding)?,
ValueInformation::new(Some(all_bytes.clone()), value_pieces),
))
}
/// Evaluate and parse the type by going down the tree of type dies.
///
/// Description:
///
/// * `registers` - A register struct for accessing the register values.
/// * `mem` - A struct for accessing the memory of the debug target.
/// * `dwarf` - A reference to gimli-rs `Dwarf` struct.
/// * `unit` - A compilation unit which contains the given DIE.
/// * `die` - The current type die in the type tree.
/// * `data_offset` - The memory address offset.
/// * `pieces` - A list of pieces containing the location and size information.
fn eval_type<M: MemoryAccess>(
registers: &Registers,
mem: &mut M,
dwarf: &gimli::Dwarf<R>,
unit: &gimli::Unit<R>,
die: &gimli::DebuggingInformationEntry<'_, '_, R>,
data_offset: u64,
pieces: &mut Vec<MyPiece<R>>,
) -> Result<EvaluatorValue<R>> {
info!("tag: {:?}", die.tag());
match die.tag() {
gimli::DW_TAG_base_type => {
// Make sure that the die has the tag DW_TAG_base_type.
match die.tag() {
gimli::DW_TAG_base_type => (),
_ => {
error!("Expected DW_TAG_base_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_base_type die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
// Get byte size and encoding from the die.
let byte_size = match attributes::byte_size_attribute(die)? {
Some(val) => val,
None => {
error!("Missing required byte size attribute");
return Err(anyhow!("Missing required byte size attribute"));
}
};
if byte_size == 0 {
return Ok(EvaluatorValue::ZeroSize);
}
let encoding = match attributes::encoding_attribute(die)? {
Some(val) => val,
None => {
error!("Missing required encoding attribute");
return Err(anyhow!("Missing required encoding attribute"));
}
};
// Evaluate the value.
EvaluatorValue::handle_eval_piece(
registers,
mem,
byte_size,
data_offset, // TODO
encoding,
pieces,
)
}
gimli::DW_TAG_pointer_type => {
info!("DW_TAG_pointer_type");
// Make sure that the die has the tag DW_TAG_pointer_type.
match die.tag() {
gimli::DW_TAG_pointer_type => (),
_ => {
error!("Expected DW_TAG_pointer_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_pointer_type die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
// Get the name of the pointer type.
let name = attributes::name_attribute(dwarf, die)?;
// Evaluate the pointer type value.
let address_class = match attributes::address_class_attribute(die)? {
Some(val) => val,
None => {
error!("Die is missing required attribute DW_AT_address_class");
return Err(anyhow!(
"Die is missing required attribute DW_AT_address_class"
));
}
};
// This vill evaluate the address
let address = match address_class.0 {
0 => {
EvaluatorValue::handle_eval_piece(
registers,
mem,
4, // This Should be set dependent on the system(4 for 32 bit systems)
data_offset,
DwAte(1),
pieces,
)?
}
_ => {
error!("Unimplemented DwAddr code"); // NOTE: The codes are architecture specific.
return Err(anyhow!("Unimplemented DwAddr code"));
}
};
let value = match (attributes::type_attribute(dwarf, unit, die)?, &address) {
(
Some((section_offset, unit_offset)),
EvaluatorValue::Value(BaseTypeValue::Address32(address_value), _),
) => {
// Get the variable die.
let header = dwarf.debug_info.header_from_offset(
match section_offset.as_debug_info_offset() {
Some(val) => val,
None => {
error!(
"Could not convert section offset into debug info offset"
);
return Err(anyhow!(
"Could not convert section offset into debug info offset"
));
}
},
)?;
let type_unit = gimli::Unit::new(dwarf, header)?;
let type_die = type_unit.entry(unit_offset)?;
let mut new_pieces = vec![MyPiece::new(Piece {
size_in_bits: None,
bit_offset: None,
location: Location::<R>::Address {
address: *address_value as u64,
},
})];
EvaluatorValue::eval_type(
registers,
mem,
dwarf,
&type_unit,
&type_die,
0,
&mut new_pieces,
)?
}
_ => EvaluatorValue::OptimizedOut,
};
Ok(EvaluatorValue::PointerTypeValue(Box::new(
PointerTypeValue {
name,
address,
value,
},
)))
// TODO: Use DW_AT_type and the evaluated address to evaluate the pointer.
}
gimli::DW_TAG_array_type => {
// Make sure that the die has the tag DW_TAG_array_type.
match die.tag() {
gimli::DW_TAG_array_type => (),
_ => {
error!("Expected DW_TAG_array_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_array_type die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
let mut children = get_children(unit, die)?;
let mut i = 0;
while i < children.len() {
let die = unit.entry(children[i])?;
match die.tag() {
gimli::DW_TAG_subrange_type => (),
_ => {
let _c = children.remove(i);
i -= 1;
}
}
i += 1;
}
if children.len() != 1 {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
let dimension_die = unit.entry(children[0])?;
let subrange_type_value = match EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
&dimension_die,
data_offset,
pieces,
)? {
EvaluatorValue::SubrangeTypeValue(subrange_type_value) => subrange_type_value,
_ => {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
};
let mut values = vec![];
// Evaluate all the values in the array.
match subrange_type_value.get_count()? {
Some(count) => {
// Get type attribute unit and die.
let (type_unit, die_offset) = get_type_info(dwarf, unit, die)?;
let type_die = &type_unit.entry(die_offset)?;
// Evaluate all the values in the array.
for _i in 0..count {
values.push(EvaluatorValue::eval_type(
registers,
mem,
dwarf,
&type_unit,
type_die,
data_offset,
pieces,
)?);
}
}
None => (),
};
Ok(EvaluatorValue::Array(Box::new(ArrayTypeValue {
subrange_type_value,
values,
})))
}
gimli::DW_TAG_structure_type => {
// Make sure that the die has the tag DW_TAG_structure_type.
match die.tag() {
gimli::DW_TAG_structure_type => (),
_ => {
error!("Expected DW_TAG_structure_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_structure_type die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
let name = match attributes::name_attribute(dwarf, die)? {
Some(val) => val,
None => {
error!("Expected the structure type die to have a name attribute");
return Err(anyhow!(
"Expected the structure type die to have a name attribute"
));
}
};
// Get all the DW_TAG_member dies.
let children = get_children(unit, die)?;
let mut member_dies = Vec::new();
for c in &children {
let c_die = unit.entry(*c)?;
match c_die.tag() {
// If it is a DW_TAG_variant_part die then it is a enum and only have on value.
gimli::DW_TAG_variant_part => {
// Get the value.
let members = vec![EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
&c_die,
data_offset,
pieces,
)?];
return Ok(EvaluatorValue::Struct(Box::new(StructureTypeValue {
name,
members,
})));
}
gimli::DW_TAG_member => {
let data_member_location =
match attributes::data_member_location_attribute(&c_die)? {
Some(val) => val,
None => {
error!(
"Expected member die to have attribute DW_AT_data_member_location"
);
return Err(
anyhow!(
"Expected member die to have attribute DW_AT_data_member_location"),
);
}
};
member_dies.push((data_member_location, c_die))
}
_ => continue,
};
}
// Sort the members in the evaluation order.
member_dies.sort_by_key(|m| m.0);
// Evaluate all the members.
let mut members = vec![];
for member_die in &member_dies {
let member = match member_die.1.tag() {
gimli::DW_TAG_member => EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
&member_die.1,
data_offset,
pieces,
)?,
tag => {
error!("Unexpected die tag: {:?}", tag);
return Err(anyhow!("Unimplemented"));
}
};
members.push(member);
}
Ok(EvaluatorValue::Struct(Box::new(StructureTypeValue {
name,
members,
})))
}
gimli::DW_TAG_union_type => {
// Make sure that the die has the tag DW_TAG_union_type.
match die.tag() {
gimli::DW_TAG_union_type => (),
_ => {
error!("Expected DW_TAG_union_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_union_type die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
let name = match attributes::name_attribute(dwarf, die)? {
Some(val) => val,
None => {
error!("Expected union type die to have a name attribute");
return Err(anyhow!("Expected union type die to have a name attribute"));
}
};
// Get all children of type DW_TAG_member.
let children = get_children(unit, die)?;
let mut member_dies = vec![];
for c in children {
let c_die = unit.entry(c)?;
match c_die.tag() {
gimli::DW_TAG_member => {
let data_member_location =
match attributes::data_member_location_attribute(&c_die)? {
Some(val) => val,
None => {
error!("Expected member die to have attribute DW_AT_data_member_location");
return Err(anyhow!("Expected member die to have attribute DW_AT_data_member_location"));
}
};
member_dies.push((data_member_location, c_die))
}
_ => continue,
};
}
// Sort all the members in the order they need to be evaluated.
member_dies.sort_by_key(|m| m.0);
// Evaluate all the members.
let mut members = vec![];
for member_die in &member_dies {
let member = match member_die.1.tag() {
gimli::DW_TAG_member => EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
&member_die.1,
data_offset,
pieces,
)?,
tag => {
error!("Unexpected die with tag {:?}", tag);
return Err(anyhow!("Unimplemented"));
}
};
members.push(member);
}
Ok(EvaluatorValue::Union(Box::new(UnionTypeValue {
name,
members,
})))
}
gimli::DW_TAG_member => {
// Make sure that the die has the tag DW_TAG_member
match die.tag() {
gimli::DW_TAG_member => (),
_ => {
error!("Expected DW_TAG_member die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_member die, this should never happen"
));
}
};
// Get the name of the member.
let name = attributes::name_attribute(dwarf, die)?;
// Calculate the new data offset.
let new_data_offset = match attributes::data_member_location_attribute(die)? {
// NOTE: Seams it can also be a location description and not an offset. Dwarf 5 page 118
Some(val) => data_offset + val,
None => data_offset,
};
check_alignment(die, new_data_offset, pieces)?;
// Get the type attribute unit and die.
let (type_unit, die_offset) = get_type_info(dwarf, unit, die)?;
let type_die = &type_unit.entry(die_offset)?;
// Evaluate the value.
let value = EvaluatorValue::eval_type(
registers,
mem,
dwarf,
&type_unit,
type_die,
new_data_offset,
pieces,
)?;
Ok(EvaluatorValue::Member(Box::new(MemberValue {
name,
value,
})))
}
gimli::DW_TAG_enumeration_type => {
// Make sure that the die has the tag DW_TAG_enumeration_type
match die.tag() {
gimli::DW_TAG_enumeration_type => (),
_ => {
error!("Expected DW_TAG_enumeration_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_enumeration_type die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
// Get type attribute unit and die.
let (type_unit, die_offset) = get_type_info(dwarf, unit, die)?;
let type_die = &type_unit.entry(die_offset)?;
// Get type value.
let variant = EvaluatorValue::eval_type(
registers,
mem,
dwarf,
&type_unit,
type_die,
data_offset,
pieces,
)?;
// Go through the children and find the correct enumerator value.
let children = get_children(unit, die)?;
let mut enumerators = vec![];
for c in children {
let c_die = unit.entry(c)?;
match c_die.tag() {
gimli::DW_TAG_enumerator => {
let name = attributes::name_attribute(dwarf, &c_die)?;
let const_value = match attributes::const_value_attribute(&c_die)? {
Some(val) => val,
None => {
error!("Expected enumeration type die to have attribute DW_AT_const_value");
return Err(anyhow!("Expected enumeration type die to have attribute DW_AT_const_value"));
}
};
enumerators.push(EnumeratorValue { name, const_value });
}
gimli::DW_TAG_subprogram => (),
tag => {
error!("Unimplemented for tag: {:?}", tag);
return Err(anyhow!("Unimplemented"));
}
};
}
// Get the name of the enum type and the enum variant.
let name = match attributes::name_attribute(dwarf, die)? {
Some(val) => val,
None => {
error!("Expected enumeration type die to have attribute DW_AT_name");
return Err(anyhow!(
"Expected enumeration type die to have attribute DW_AT_name"
));
}
};
Ok(EvaluatorValue::Enum(Box::new(EnumerationTypeValue {
name,
variant,
enumerators,
})))
}
gimli::DW_TAG_variant_part => {
// Make sure that the die has tag DW_TAG_variant_part
match die.tag() {
gimli::DW_TAG_variant_part => (),
_ => {
error!("Expected DW_TAG_variant_part die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_variant_part die, this should never happen"
));
}
};
check_alignment(die, data_offset, pieces)?;
// Get the enum variant.
// TODO: If variant is optimised out then return optimised out and remove the pieces for
// this type if needed.
let variant: Option<MemberValue<R>> = match attributes::discr_attribute(die)? {
Some(die_offset) => {
let member_die = &unit.entry(die_offset)?;
// Evaluate the DW_TAG_member value.
match member_die.tag() {
gimli::DW_TAG_member => match EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
member_die,
data_offset,
pieces,
)? {
EvaluatorValue::Member(member) => Some(*member),
_ => {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
},
_ => {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
}
}
None => None,
};
// The value should be a unsigned int thus convert the value to a u64.
let variant_number = match variant.clone() {
Some(MemberValue { name: _name, value }) => match value.to_value() {
Some(val) => Some(get_udata(val)?),
None => None,
},
None => None,
};
let original_pieces = pieces.clone();
// Find all the DW_TAG_variant dies and evaluate them.
let mut variants = vec![];
let children = get_children(unit, die)?;
for c in &children {
let c_die = unit.entry(*c)?;
if c_die.tag() == gimli::DW_TAG_variant {
let mut temp_pieces = original_pieces.clone();
// Evaluate the value of the variant.
let variant = match EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
&c_die,
data_offset,
&mut temp_pieces,
)? {
EvaluatorValue::VariantValue(variant) => variant,
_ => {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
};
if let (Some(discr_value), Some(variant_num)) =
(variant.discr_value, variant_number)
{
// If This is the variant then update the piece index.
if discr_value == variant_num {
*pieces = temp_pieces;
}
};
variants.push(*variant);
};
}
Ok(EvaluatorValue::VariantPartValue(Box::new(
VariantPartValue { variant, variants },
)))
}
gimli::DW_TAG_variant => {
check_alignment(die, data_offset, pieces)?;
let mut members = vec![];
// Find the child die of type DW_TAG_member
let children = get_children(unit, die)?;
for c in children {
let c_die = unit.entry(c)?;
if c_die.tag() == gimli::DW_TAG_member {
// Evaluate the value of the member.
let member = match EvaluatorValue::eval_type(
registers,
mem,
dwarf,
unit,
&c_die,
data_offset,
pieces,
)? {
EvaluatorValue::Member(member) => member,
_ => {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
};
members.push(member);
};
}
if members.len() != 1 {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
// DW_TAG_variant should only have one member child.
}
let discr_value = attributes::discr_value_attribute(die)?;
Ok(EvaluatorValue::VariantValue(Box::new(VariantValue {
discr_value,
child: *members[0].clone(),
})))
}
gimli::DW_TAG_subrange_type => {
// Make sure that the die has the tag DW_TAG_subrange_type
match die.tag() {
gimli::DW_TAG_subrange_type => (),
_ => {
error!("Expected DW_TAG_subrange_type die, this should never happen");
return Err(anyhow!(
"Expected DW_TAG_subrange_type die, this should never happen"
));
}
};
let lower_bound = attributes::lower_bound_attribute(die)?;
// If the die has a count attribute then that is the value.
match attributes::count_attribute(die)? {
// NOTE: This could be replace with lower and upper bound
Some(count) => Ok(EvaluatorValue::SubrangeTypeValue(SubrangeTypeValue {
lower_bound,
count: Some(count),
base_type_value: None,
})),
None => {
// Get the type unit and die.
let (type_unit, die_offset) = match get_type_info(dwarf, unit, die) {
Ok(val) => val,
Err(_) => {
error!("Expected subrange type die to have type information");
return Err(anyhow!(
"Expected subrange type die to have type information"
));
}
};
let type_die = &type_unit.entry(die_offset)?;
// Evaluate the type attribute value.
let base_type_value = match EvaluatorValue::eval_type(
registers,
mem,
dwarf,
&type_unit,
type_die,
data_offset,
pieces,
)? {
EvaluatorValue::Value(base_type_value, value_information) => {
Some((base_type_value, value_information))
}
_ => {
error!("Unreachable");
return Err(anyhow!("Unreachable"));
}
};
Ok(EvaluatorValue::SubrangeTypeValue(SubrangeTypeValue {
lower_bound,
count: None,
base_type_value,
}))
}
}
}
gimli::DW_TAG_subroutine_type => {
error!("Unimplemented");
Err(anyhow!("Unimplemented"))
}
gimli::DW_TAG_subprogram => {
error!("Unimplemented");
Err(anyhow!("Unimplemented"))
}
gimli::DW_TAG_string_type => {
error!("Unimplemented");
Err(anyhow!("Unimplemented"))
}
gimli::DW_TAG_generic_subrange => {
error!("Unimplemented");
Err(anyhow!("Unimplemented"))
}
gimli::DW_TAG_template_type_parameter => {
error!("Unimplemented");
Err(anyhow!("Unimplemented"))
}
tag => {
error!("Unimplemented for tag {:?}", tag);
Err(anyhow!("Unimplemented"))
}
}
}
}
/// Parse a `BaseTypeValue` struct to a `u64` value.
///
/// Description:
///
/// * `value` - The `BaseTypeValue` that will be turned into a `u64`.
pub fn get_udata(value: BaseTypeValue) -> Result<u64> {
match value {
BaseTypeValue::U8(v) => Ok(v as u64),
BaseTypeValue::U16(v) => Ok(v as u64),
BaseTypeValue::U32(v) => Ok(v as u64),
BaseTypeValue::U64(v) => Ok(v),
BaseTypeValue::Generic(v) => Ok(v),
_ => {
error!("Unimplemented");
Err(anyhow!("Unimplemented"))
}
}
}
/// Format a `Vec` of `EvaluatorValue`s into a `String` that describes the value and type.
///
/// Description:
///
/// * `values` - A list of `EvaluatorValue`s that will be formatted into a `String`.
fn format_values<R: Reader<Offset = usize>>(values: &Vec<EvaluatorValue<R>>) -> String {
let len = values.len();
if len == 0 {
return "".to_string();
} else if len == 1 {
return format!("{}", values[0]);
}
let mut res = format!("{}", values[0]);
for value in values.iter().take(len).skip(1) {
res = format!("{}, {}", res, value);
}
res
}
/// Format a `Vec` of `EvaluatorValue`s into a `String` that describes the type.
///
/// Description:
///
/// * `values` - A list of `EvaluatorValue`s that will be formatted into a `String`.
fn format_types<R: Reader<Offset = usize>>(values: &Vec<EvaluatorValue<R>>) -> String {
let len = values.len();
if len == 0 {
return "".to_string();
} else if len == 1 {
return values[0].get_type();
}
let mut res = values[0].get_type();
for value in values.iter().take(len).skip(1) {
res = format!("{}, {}", res, value.get_type());
}
res
}
/// Struct that represents a array type.
#[derive(Debug, Clone)]
pub struct ArrayTypeValue<R: Reader<Offset = usize>> {
/// subrange_type information.
pub subrange_type_value: SubrangeTypeValue,
/// The list of values in the array.
pub values: Vec<EvaluatorValue<R>>,
}
impl<R: Reader<Offset = usize>> fmt::Display for ArrayTypeValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[ {} ]", format_values(&self.values))
}
}
impl<R: Reader<Offset = usize>> ArrayTypeValue<R> {
/// Get the type of the array as a `String`.
pub fn get_type(&self) -> String {
format!("[ {} ]", format_types(&self.values))
}
}
/// Struct that represents a struct type.
#[derive(Debug, Clone)]
pub struct StructureTypeValue<R: Reader<Offset = usize>> {
/// The name of the struct.
pub name: String,
/// All the attributes of the struct.
pub members: Vec<EvaluatorValue<R>>,
}
impl<R: Reader<Offset = usize>> fmt::Display for StructureTypeValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {{ {} }}", self.name, format_values(&self.members))
}
}
impl<R: Reader<Offset = usize>> StructureTypeValue<R> {
/// Get the type of the struct as a `String`.
pub fn get_type(&self) -> String {
format!("{} {{ {} }}", self.name, format_types(&self.members))
}
}
/// Struct that represents a enum type.
#[derive(Debug, Clone)]
pub struct EnumerationTypeValue<R: Reader<Offset = usize>> {
/// The name of the Enum.
pub name: String,
/// The name of the Enum.
pub variant: EvaluatorValue<R>,
/// The value of the enum.
pub enumerators: Vec<EnumeratorValue>,
}
impl<R: Reader<Offset = usize>> fmt::Display for EnumerationTypeValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}::{}", self.name, self.variant)
}
}
impl<R: Reader<Offset = usize>> EnumerationTypeValue<R> {
/// Get the type of the enum as a `String`.
pub fn get_type(&self) -> String {
format!("{}::{}", self.name, self.variant.get_type())
}
}
/// Struct that represents a union type.
#[derive(Debug, Clone)]
pub struct UnionTypeValue<R: Reader<Offset = usize>> {
/// The name of the union type
pub name: String,
/// The values of the union type.
pub members: Vec<EvaluatorValue<R>>,
}
impl<R: Reader<Offset = usize>> fmt::Display for UnionTypeValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} ( {} )", self.name, format_values(&self.members))
}
}
impl<R: Reader<Offset = usize>> UnionTypeValue<R> {
/// Get the type of the union as a `String`.
pub fn get_type(&self) -> String {
format!("{} ( {} )", self.name, format_types(&self.members))
}
}
/// Struct that represents a attribute type.
#[derive(Debug, Clone)]
pub struct MemberValue<R: Reader<Offset = usize>> {
/// The name of the attribute.
pub name: Option<String>,
/// The value of the attribute.
pub value: EvaluatorValue<R>,
}
impl<R: Reader<Offset = usize>> fmt::Display for MemberValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.name {
Some(name) => write!(f, "{}::{}", name, self.value),
None => write!(f, "{}", self.value),
}
}
}
impl<R: Reader<Offset = usize>> MemberValue<R> {
/// Get the type of the attribute as a `String`.
pub fn get_type(&self) -> String {
match &self.name {
Some(name) => format!("{}::{}", name, self.value.get_type()),
None => self.value.get_type(),
}
}
}
/// Struct that represents a pointer type.
#[derive(Debug, Clone)]
pub struct PointerTypeValue<R: Reader<Offset = usize>> {
/// The name of the pointer type.
pub name: Option<String>,
/// The value of the attribute.
pub address: EvaluatorValue<R>,
/// The value stored at the pointed location
pub value: EvaluatorValue<R>,
// DW_TAG_pointer_type contains:
// * DW_AT_type
// * DW_AT_name
// * DW_AT_address_class
}
impl<R: Reader<Offset = usize>> fmt::Display for PointerTypeValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.name {
Some(name) => write!(f, "{}::{}", name, self.value),
None => write!(f, "{}", self.value),
}
}
}
impl<R: Reader<Offset = usize>> PointerTypeValue<R> {
/// Get the type of the pointer type as a `String`.
pub fn get_type(&self) -> String {
match &self.name {
Some(name) => format!("{}::{}", name, self.value.get_type()),
None => self.value.get_type(),
}
}
}
/// Struct that represents a enumerator.
#[derive(Debug, Clone)]
pub struct EnumeratorValue {
/// The name of the enumerator.
pub name: Option<String>,
/// The value of the attribute.
pub const_value: u64,
// DW_TAG_enumerator contains:
// * DW_AT_name
// * DW_AT_const_value
}
impl fmt::Display for EnumeratorValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.name {
Some(name) => write!(f, "{}::{}", name, self.const_value),
None => write!(f, "{}", self.const_value),
}
}
}
impl EnumeratorValue {
/// Get the type of the enumerator as a `String`.
pub fn get_type(&self) -> String {
format!("{:?}", self.name)
}
}
/// Struct that represents a variant.
#[derive(Debug, Clone)]
pub struct VariantValue<R: Reader<Offset = usize>> {
/// The discr value
pub discr_value: Option<u64>,
/// The child value
pub child: MemberValue<R>,
// DW_TAG_variant contains:
// * DW_AT_discr_value
// * A child with tag DW_TAG_member
}
impl<R: Reader<Offset = usize>> fmt::Display for VariantValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.discr_value {
Some(discr) => write!(f, "{}::{}", discr, self.child),
None => write!(f, "{}", self.child),
}
}
}
impl<R: Reader<Offset = usize>> VariantValue<R> {
/// Get the type of the variant as a `String`.
pub fn get_type(&self) -> String {
match &self.discr_value {
Some(discr) => format!("{} {}", discr, self.child.get_type()),
None => self.child.get_type(),
}
}
}
/// Struct that represents a variant_part.
#[derive(Debug, Clone)]
pub struct VariantPartValue<R: Reader<Offset = usize>> {
/// The variant value
pub variant: Option<MemberValue<R>>,
/// The variants
pub variants: Vec<VariantValue<R>>,
// DW_TAG_variant_part contains:
// * DW_AT_discr_value
// * A child with tag DW_TAG_member
// * Children with tag DW_TAG_variant
}
impl<R: Reader<Offset = usize>> fmt::Display for VariantPartValue<R> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut variants = "{".to_string();
for v in &self.variants {
variants = format!("{} {},", variants, v);
}
variants = format!("{} {}", variants, "}");
match &self.variant {
// TODO: Improve
Some(variant) => write!(f, "< variant: {} >, {}", variant, variants),
None => write!(f, "{}", variants),
}
}
}
impl<R: Reader<Offset = usize>> VariantPartValue<R> {
/// Get the type of the variant_part as a `String`.
pub fn get_type(&self) -> String {
// TODO: Improve
match &self.variant {
Some(variant) => variant.to_string(),
None => "".to_owned(),
}
}
}
/// Struct that represents a variant.
#[derive(Debug, Clone)]
pub struct SubrangeTypeValue {
/// The lowser bound
pub lower_bound: Option<u64>,
/// The count
pub count: Option<u64>,
/// The count value but evaluated. // TODO: Combine count and number to one attriute.
pub base_type_value: Option<(BaseTypeValue, ValueInformation)>,
// DW_TAG_variant contains:
// * DW_AT_type
// * DW_AT_lower_bound
// * DW_AT_count
}
impl fmt::Display for SubrangeTypeValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.get_count() {
Ok(Some(count)) => write!(f, "{}", count),
_ => write!(f, ""),
}
}
}
impl SubrangeTypeValue {
/// Get the type of the subrange_type as a `String`.
pub fn get_type(&self) -> String {
match &self.base_type_value {
Some((val, _)) => val.get_type(),
None => "u64".to_string(),
}
}
pub fn get_count(&self) -> Result<Option<u64>> {
match self.count {
Some(val) => Ok(Some(val)),
None => match &self.base_type_value {
Some((btv, _)) => Ok(Some(get_udata(btv.clone())?)),
None => Ok(None),
},
}
}
}
/// A enum representing the base types in DWARF.
#[derive(Debug, Clone)]
pub enum BaseTypeValue {
/// generic value.
Generic(u64),
/// 32 bit address.
Address32(u32),
/// 32 bit register value.
Reg32(u32),
/// boolean
Bool(bool),
/// 8 bit unsigned integer.
U8(u8),
/// 16 bit unsigned integer.
U16(u16),
/// 32 bit unsigned integer.
U32(u32),
/// 64 bit unsigned integer.
U64(u64),
/// 8 bit signed integer.
I8(i8),
/// 16 bit signed integer.
I16(i16),
/// 32 bit signed integer.
I32(i32),
/// 64 bit signed integer.
I64(i64),
/// 32 bit float.
F32(f32),
/// 64 bit float.
F64(f64),
}
impl fmt::Display for BaseTypeValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
BaseTypeValue::Bool(val) => write!(f, "{}", val),
BaseTypeValue::Generic(val) => write!(f, "{}", val),
BaseTypeValue::I8(val) => write!(f, "{}", val),
BaseTypeValue::U8(val) => write!(f, "{}", val),
BaseTypeValue::I16(val) => write!(f, "{}", val),
BaseTypeValue::U16(val) => write!(f, "{}", val),
BaseTypeValue::I32(val) => write!(f, "{}", val),
BaseTypeValue::U32(val) => write!(f, "{}", val),
BaseTypeValue::I64(val) => write!(f, "{}", val),
BaseTypeValue::U64(val) => write!(f, "{}", val),
BaseTypeValue::F32(val) => write!(f, "{}", val),
BaseTypeValue::F64(val) => write!(f, "{}", val),
BaseTypeValue::Address32(val) => write!(f, "'Address' {:#10x}", val),
BaseTypeValue::Reg32(val) => write!(f, "0x{:x}", val),
}
}
}
impl BaseTypeValue {
/// Parse a DWARF base type.
///
/// Description:
///
/// * `data` - The value in bytes.
/// * `encoding` - The DWARF encoding of the value.
///
/// Will parse the given bytes into the encoding type.
/// The size of the given `data` parameter will be used when parsing.
pub fn parse_base_type(data: Vec<u8>, encoding: DwAte) -> Result<BaseTypeValue> {
if data.is_empty() {
return Err(anyhow!("Expected data to be larger then 0"));
}
// TODO: Fix so not any data size can be sent into this function.
Ok(match (encoding, data.len()) {
// Source: DWARF 4 page 168-169 and 77
(DwAte(1), 4) => BaseTypeValue::Address32(u32::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // DW_ATE_address = 1 // TODO: Different size addresses?
(DwAte(2), 1) => BaseTypeValue::Bool(
(u8::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})) == 1,
), // DW_ATE_boolean = 2 // TODO: Use modulus?
(DwAte(2), 2) => BaseTypeValue::Bool(
(u16::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})) == 1,
), // DW_ATE_boolean = 2 // TODO: Use modulus?
(DwAte(2), 4) => BaseTypeValue::Bool(
(u32::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})) == 1,
), // DW_ATE_boolean = 2 // TODO: Use modulus?
// (DwAte(3), _) => , // DW_ATE_complex_float = 3 // NOTE: Seems like a C++ thing
(DwAte(4), 4) => BaseTypeValue::F32(f32::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // DW_ATE_float = 4
(DwAte(4), 8) => BaseTypeValue::F64(f64::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // DW_ATE_float = 4
(DwAte(5), 1) => BaseTypeValue::I8(i8::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_signed = 5, 8)
(DwAte(5), 2) => BaseTypeValue::I16(i16::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_signed = 5, 16)
(DwAte(5), 4) => BaseTypeValue::I32(i32::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_signed = 5, 32)
(DwAte(5), 8) => BaseTypeValue::I64(i64::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_signed = 5, 64)
// (DwAte(6), _) => , // DW_ATE_signed_char = 6 // TODO: Add type
(DwAte(7), 1) => BaseTypeValue::U8(u8::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_unsigned = 7, 8)
(DwAte(7), 2) => BaseTypeValue::U16(u16::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_unsigned = 7, 16)
(DwAte(7), 4) => BaseTypeValue::U32(u32::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_unsigned = 7, 32)
(DwAte(7), 8) => BaseTypeValue::U64(u64::from_le_bytes(match data.try_into() {
Ok(val) => val,
Err(err) => {
error!("{:?}", err);
return Err(anyhow!("{:?}", err));
}
})), // (DW_ATE_unsigned = 7, 64)
_ => {
error!("encoding {}, byte_size: {}", encoding, data.len());
return Err(anyhow!("encoding {}, byte_size: {}", encoding, data.len()));
}
})
}
/// Get the base type as a `String` with the Rust names.
pub fn get_type(&self) -> String {
match self {
BaseTypeValue::Bool(_) => "bool".to_owned(),
BaseTypeValue::Generic(_) => "<unknown>".to_owned(),
BaseTypeValue::I8(_) => "i8".to_owned(),
BaseTypeValue::U8(_) => "u8".to_owned(),
BaseTypeValue::I16(_) => "i16".to_owned(),
BaseTypeValue::U16(_) => "u16".to_owned(),
BaseTypeValue::I32(_) => "i32".to_owned(),
BaseTypeValue::U32(_) => "u32".to_owned(),
BaseTypeValue::I64(_) => "i64".to_owned(),
BaseTypeValue::U64(_) => "u64".to_owned(),
BaseTypeValue::F32(_) => "f32".to_owned(),
BaseTypeValue::F64(_) => "f63".to_owned(),
BaseTypeValue::Address32(_) => "<32 bit address>".to_owned(),
BaseTypeValue::Reg32(_) => "<32 bit register value>".to_owned(),
}
}
}
/// Convert a `BaseTypeValue` to a `gimli::Value`.
///
/// Description:
///
/// * `value` - The value that will be converted into a `gimli::Value` stuct.
pub fn convert_to_gimli_value(value: BaseTypeValue) -> gimli::Value {
match value {
BaseTypeValue::Bool(val) => gimli::Value::Generic(match val {
true => 1,
false => 0,
}),
BaseTypeValue::Generic(val) => gimli::Value::Generic(val),
BaseTypeValue::I8(val) => gimli::Value::I8(val),
BaseTypeValue::U8(val) => gimli::Value::U8(val),
BaseTypeValue::I16(val) => gimli::Value::I16(val),
BaseTypeValue::U16(val) => gimli::Value::U16(val),
BaseTypeValue::I32(val) => gimli::Value::I32(val),
BaseTypeValue::U32(val) => gimli::Value::U32(val),
BaseTypeValue::I64(val) => gimli::Value::I64(val),
BaseTypeValue::U64(val) => gimli::Value::U64(val),
BaseTypeValue::F32(val) => gimli::Value::F32(val),
BaseTypeValue::F64(val) => gimli::Value::F64(val),
BaseTypeValue::Address32(val) => gimli::Value::Generic(val as u64),
BaseTypeValue::Reg32(val) => gimli::Value::U32(val),
}
}
/// Convert a `gimli::Value` to a `BaseTypeValue`.
///
/// Description:
///
/// * `value` - The value that will be converted into a `BaseTypeValue` stuct.
pub fn convert_from_gimli_value(value: gimli::Value) -> BaseTypeValue {
match value {
gimli::Value::Generic(val) => BaseTypeValue::Generic(val),
gimli::Value::I8(val) => BaseTypeValue::I8(val),
gimli::Value::U8(val) => BaseTypeValue::U8(val),
gimli::Value::I16(val) => BaseTypeValue::I16(val),
gimli::Value::U16(val) => BaseTypeValue::U16(val),
gimli::Value::I32(val) => BaseTypeValue::I32(val),
gimli::Value::U32(val) => BaseTypeValue::U32(val),
gimli::Value::I64(val) => BaseTypeValue::I64(val),
gimli::Value::U64(val) => BaseTypeValue::U64(val),
gimli::Value::F32(val) => BaseTypeValue::F32(val),
gimli::Value::F64(val) => BaseTypeValue::F64(val),
}
}
/// Will retrieve the type DIE and compilation unit for a given die.
///
/// Description:
///
/// * `dwarf` - A reference to gimli-rs `Dwarf` struct.
/// * `unit` - A compilation unit which contains the given DIE.
/// * `die` - The DIE which contain a reference to the type DIE.
fn get_type_info<R: Reader<Offset = usize>>(
dwarf: &gimli::Dwarf<R>,
unit: &gimli::Unit<R>,
die: &gimli::DebuggingInformationEntry<'_, '_, R>,
) -> Result<(gimli::Unit<R>, gimli::UnitOffset)> {
let (unit_offset, die_offset) = match attributes::type_attribute(dwarf, unit, die)? {
Some(val) => val,
None => {
error!("Die doesn't have the required DW_AT_type attribute");
return Err(anyhow!(
"Die doesn't have the required DW_AT_type attribute"
));
}
};
let unit = match unit_offset {
gimli::UnitSectionOffset::DebugInfoOffset(offset) => {
let header = dwarf.debug_info.header_from_offset(offset)?;
dwarf.unit(header)?
}
gimli::UnitSectionOffset::DebugTypesOffset(_offset) => {
let mut iter = dwarf.debug_types.units();
let mut result = None;
while let Some(header) = iter.next()? {
if header.offset() == unit_offset {
result = Some(dwarf.unit(header)?);
break;
}
}
match result {
Some(val) => val,
None => {
error!("Could not get unit from unit offset");
return Err(anyhow!("Could not get unit from unit offset"));
}
}
}
};
Ok((unit, die_offset))
}
/// Will check that the address is correctly aligned.
///
/// Description:
///
/// * `die` - The type DIE to check alignment for.
/// * `data_offset` - The memory address offset.
/// * `pieces` - A list of pieces containing the location and size information.
fn check_alignment<R: Reader<Offset = usize>>(
die: &gimli::DebuggingInformationEntry<'_, '_, R>,
mut data_offset: u64,
pieces: &Vec<MyPiece<R>>,
) -> Result<()> {
match attributes::alignment_attribute(die)? {
Some(alignment) => {
if pieces.is_empty() {
return Ok(());
}
if pieces.is_empty() {
data_offset = 0;
}
if let Location::Address { address } = pieces[0].piece.location {
let mut addr = address + (data_offset / 4) * 4;
addr -= addr % 4; // TODO: Is this correct?
if addr % alignment != 0 {
error!("Address not aligned");
return Err(anyhow!("Address not aligned"));
}
};
}
None => (),
};
Ok(())
}
/// Will retrieve the list of children DIEs for a DIE.
///
/// Description:
///
/// * `unit` - The compilation unit which contains the given DIE.
/// * `die` - The DIE to find the children for.
fn get_children<R: Reader<Offset = usize>>(
unit: &gimli::Unit<R>,
die: &gimli::DebuggingInformationEntry<'_, '_, R>,
) -> Result<Vec<gimli::UnitOffset>> {
let mut result = Vec::new();
let mut tree = unit.entries_tree(Some(die.offset()))?;
let node = tree.root()?;
let mut children = node.children();
while let Some(child) = children.next()? {
result.push(child.entry().offset());
}
Ok(result)
}
/// Will remove the unnecessary bytes.
///
/// Description:
///
/// * `bytes` - The bytes to be trimmed of unnecessary bytes.
/// * `piece` - The piece the given bytes is evaluated from.
/// * `byte_size` - The byte size of the resulting trim.
///
/// Some pieces contain more bytes then the type describes.
/// Thus this function removes those unused bytes.
fn trim_piece_bytes<R: Reader<Offset = usize>>(
mut bytes: Vec<u8>,
piece: &Piece<R>,
byte_size: usize,
) -> Vec<u8> {
let piece_byte_size = match piece.size_in_bits {
Some(size) => ((size + 8 - 1) / 8) as usize,
None => byte_size,
};
let piece_byte_offset = match piece.bit_offset {
Some(offset) => {
//if offset % 8 == 0 {
// error!("Expected the offset to be in bytes, got {} bits", offset);
// return Err(anyhow!("Expected the offset to be in bytes, got {} bits", offset));
//}
((offset + 8 - 1) / 8) as usize
}
None => 0,
};
for _ in 0..piece_byte_offset {
bytes.pop();
}
while bytes.len() > piece_byte_size {
// TODO: Check that this follows the ABI.
bytes.remove(0);
}
bytes
}
/// Contains the unparsed value and the location of it.
#[derive(Debug, Clone)]
pub struct ValueInformation {
pub raw: Option<Vec<u8>>, // byte size and raw value
pub pieces: Vec<ValuePiece>,
}
impl ValueInformation {
/// Create a new `ValueInformation` struct
///
/// Description:
///
/// * `raw` - The unparsed value.
/// * `pieces` - The location of the value.
pub fn new(raw: Option<Vec<u8>>, pieces: Vec<ValuePiece>) -> ValueInformation {
ValueInformation { raw, pieces }
}
}
/// A struct that describes the size and location of a value.
#[derive(Debug, Clone)]
pub enum ValuePiece {
/// Contains which register the value is located and the size of it.
Register {
/// The register the value is stored.
register: u16,
/// The size of the value.
byte_size: usize,
},
/// Contains which address the value is located and the size of it.
Memory {
/// The address the value is stored.
address: u32,
/// The size of the value.
byte_size: usize,
},
/// Contains the value stored on the DWARF stack.
Dwarf {
/// The value stored on the DWARF stack.
/// If it is `None` then the value is optimized out.
value: Option<gimli::Value>,
},
/// TODO
Bytes { bytes: Vec<u8> },
}