-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathmod.rs
More file actions
2523 lines (2348 loc) · 90.9 KB
/
Copy pathmod.rs
File metadata and controls
2523 lines (2348 loc) · 90.9 KB
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
pub mod print;
use std::{
cell::RefCell,
cmp::max,
collections::{BTreeMap, BTreeSet, btree_map},
fmt::{Display, Formatter},
io::{BufRead, Cursor, Seek, SeekFrom},
num::NonZeroU32,
};
use anyhow::{Context, Result, anyhow, bail, ensure};
use num_enum::{IntoPrimitive, TryFromPrimitive, TryFromPrimitiveError};
use crate::{
array_ref,
util::reader::{Endian, FromBytes, FromReader},
};
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum TagKind {
Padding = 0x0000,
ArrayType = 0x0001,
ClassType = 0x0002,
EntryPoint = 0x0003,
EnumerationType = 0x0004,
FormalParameter = 0x0005,
GlobalSubroutine = 0x0006,
GlobalVariable = 0x0007,
Label = 0x000a,
LexicalBlock = 0x000b,
LocalVariable = 0x000c,
Member = 0x000d,
PointerType = 0x000f,
ReferenceType = 0x0010,
// aka SourceFile
CompileUnit = 0x0011,
StringType = 0x0012,
StructureType = 0x0013,
Subroutine = 0x0014,
SubroutineType = 0x0015,
Typedef = 0x0016,
UnionType = 0x0017,
UnspecifiedParameters = 0x0018,
Variant = 0x0019,
CommonBlock = 0x001a,
CommonInclusion = 0x001b,
Inheritance = 0x001c,
InlinedSubroutine = 0x001d,
Module = 0x001e,
PtrToMemberType = 0x001f,
SetType = 0x0020,
SubrangeType = 0x0021,
WithStmt = 0x0022,
// User types
MwOverlayBranch = 0x4080,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum FundType {
WideChar = 0x0000, // Likely an MW bug
Char = 0x0001,
SignedChar = 0x0002,
UnsignedChar = 0x0003,
Short = 0x0004,
SignedShort = 0x0005,
UnsignedShort = 0x0006,
Integer = 0x0007,
SignedInteger = 0x0008,
UnsignedInteger = 0x0009,
Long = 0x000a,
SignedLong = 0x000b,
UnsignedLong = 0x000c,
Pointer = 0x000d,
Float = 0x000e,
DblPrecFloat = 0x000f,
ExtPrecFloat = 0x0010,
Complex = 0x0011,
DblPrecComplex = 0x0012,
Void = 0x0014,
Boolean = 0x0015,
ExtPrecComplex = 0x0016,
Label = 0x0017,
// User types
LongLong = 0x8008,
SignedLongLong = 0x8108,
UnsignedLongLong = 0x8208,
Int128 = 0xa510,
Vec2x32Float = 0xac00,
}
impl FundType {
pub fn size(self) -> Result<u32> {
Ok(match self {
FundType::Char | FundType::SignedChar | FundType::UnsignedChar | FundType::Boolean => 1,
FundType::WideChar
| FundType::Short
| FundType::SignedShort
| FundType::UnsignedShort => 2,
FundType::Integer | FundType::SignedInteger | FundType::UnsignedInteger => 4,
FundType::Long
| FundType::SignedLong
| FundType::UnsignedLong
| FundType::Pointer
| FundType::Float => 4,
FundType::DblPrecFloat
| FundType::LongLong
| FundType::SignedLongLong
| FundType::UnsignedLongLong
| FundType::Vec2x32Float => 8,
FundType::Int128 => 16,
FundType::Void => 0,
FundType::ExtPrecFloat
| FundType::Complex
| FundType::DblPrecComplex
| FundType::ExtPrecComplex
| FundType::Label => bail!("Unhandled fundamental type {self:?}"),
})
}
pub fn name(self) -> Result<&'static str> {
Ok(match self {
FundType::WideChar => "wchar_t",
FundType::Char => "char",
FundType::SignedChar => "signed char",
FundType::UnsignedChar => "unsigned char",
FundType::Short => "short",
FundType::SignedShort => "signed short",
FundType::UnsignedShort => "unsigned short",
FundType::Integer => "int",
FundType::SignedInteger => "signed int",
FundType::UnsignedInteger => "unsigned int",
FundType::Long => "long",
FundType::SignedLong => "signed long",
FundType::UnsignedLong => "unsigned long",
FundType::Pointer => "void *",
FundType::Float => "float",
FundType::DblPrecFloat => "double",
FundType::ExtPrecFloat => "long double",
FundType::Void => "void",
FundType::Boolean => "bool",
FundType::Complex
| FundType::DblPrecComplex
| FundType::ExtPrecComplex
| FundType::Label => bail!("Unhandled fundamental type {self:?}"),
FundType::LongLong => "long long",
FundType::SignedLongLong => "signed long long",
FundType::UnsignedLongLong => "unsigned long long",
FundType::Int128 => "__int128",
FundType::Vec2x32Float => "__vec2x32float__",
})
}
pub fn parse_int(value: u16) -> Result<Self, TryFromPrimitiveError<Self>> {
if value >> 8 == 0x1 {
// Can appear in erased tags
Self::try_from(value & 0xFF)
} else {
Self::try_from(value)
}
}
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
pub enum Modifier {
MwPointerTo = 0x00, // Used in erased tags
PointerTo = 0x01,
ReferenceTo = 0x02,
Const = 0x03,
Volatile = 0x04,
// User types
}
impl Modifier {
pub fn parse_int(value: u8) -> Result<Self, TryFromPrimitiveError<Self>> {
Self::try_from(value & 0x7F) // High bit can appear in erased tags
}
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
pub enum SubscriptFormat {
FundTypeConstConst = 0x0,
FundTypeConstLocation = 0x1,
FundTypeLocationConst = 0x2,
FundTypeLocationLocation = 0x3,
UserTypeConstConst = 0x4,
UserTypeConstLocation = 0x5,
UserTypeLocationConst = 0x6,
UserTypeLocationLocation = 0x7,
ElementType = 0x8,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u8)]
pub enum LocationOp {
Register = 0x01,
BaseRegister = 0x02,
Address = 0x03,
Const = 0x04,
Deref2 = 0x05,
Deref4 = 0x06,
Add = 0x07,
// User types
MwFpReg = 0x80,
MwFpDReg = 0x81,
MwDRef8 = 0x82,
}
const FORM_MASK: u16 = 0xF;
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
enum FormKind {
Addr = 0x1,
Ref = 0x2,
Block2 = 0x3,
Block4 = 0x4,
Data2 = 0x5,
Data4 = 0x6,
Data8 = 0x7,
String = 0x8,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum AttributeKind {
Sibling = 0x0010 | (FormKind::Ref as u16),
Location = 0x0020 | (FormKind::Block2 as u16),
Name = 0x0030 | (FormKind::String as u16),
FundType = 0x0050 | (FormKind::Data2 as u16),
ModFundType = 0x0060 | (FormKind::Block2 as u16),
UserDefType = 0x0070 | (FormKind::Ref as u16),
ModUDType = 0x0080 | (FormKind::Block2 as u16),
Ordering = 0x0090 | (FormKind::Data2 as u16),
SubscrData = 0x00a0 | (FormKind::Block2 as u16),
ByteSize = 0x00b0 | (FormKind::Data4 as u16),
BitOffset = 0x00c0 | (FormKind::Data2 as u16),
BitSize = 0x00d0 | (FormKind::Data4 as u16),
ElementList = 0x00f0 | (FormKind::Block4 as u16),
StmtList = 0x0100 | (FormKind::Data4 as u16),
LowPc = 0x0110 | (FormKind::Addr as u16),
HighPc = 0x0120 | (FormKind::Addr as u16),
Language = 0x0130 | (FormKind::Data4 as u16),
Member = 0x0140 | (FormKind::Ref as u16),
Discr = 0x0150 | (FormKind::Ref as u16),
DiscrValue = 0x0160 | (FormKind::Block2 as u16),
StringLength = 0x0190 | (FormKind::Block2 as u16),
CommonReference = 0x01a0 | (FormKind::Ref as u16),
CompDir = 0x01b0 | (FormKind::String as u16),
ConstValueString = 0x01c0 | (FormKind::String as u16),
ConstValueData2 = 0x01c0 | (FormKind::Data2 as u16),
ConstValueData4 = 0x01c0 | (FormKind::Data4 as u16),
ConstValueData8 = 0x01c0 | (FormKind::Data8 as u16),
ConstValueBlock2 = 0x01c0 | (FormKind::Block2 as u16),
ConstValueBlock4 = 0x01c0 | (FormKind::Block4 as u16),
ContainingType = 0x01d0 | (FormKind::Ref as u16),
DefaultValueAddr = 0x01e0 | (FormKind::Addr as u16),
DefaultValueData2 = 0x01e0 | (FormKind::Data2 as u16),
DefaultValueData8 = 0x01e0 | (FormKind::Data8 as u16),
DefaultValueString = 0x01e0 | (FormKind::String as u16),
Friends = 0x01f0 | (FormKind::Block2 as u16),
Inline = 0x0200 | (FormKind::String as u16),
IsOptional = 0x0210 | (FormKind::String as u16),
LowerBoundRef = 0x0220 | (FormKind::Ref as u16),
LowerBoundData2 = 0x0220 | (FormKind::Data2 as u16),
LowerBoundData4 = 0x0220 | (FormKind::Data4 as u16),
LowerBoundData8 = 0x0220 | (FormKind::Data8 as u16),
Program = 0x0230 | (FormKind::String as u16),
Private = 0x0240 | (FormKind::String as u16),
Producer = 0x0250 | (FormKind::String as u16),
Protected = 0x0260 | (FormKind::String as u16),
Prototyped = 0x0270 | (FormKind::String as u16),
Public = 0x0280 | (FormKind::String as u16),
PureVirtual = 0x0290 | (FormKind::String as u16),
PureVirtualBlock2 = 0x0290 | (FormKind::Block2 as u16),
ReturnAddr = 0x02a0 | (FormKind::Block2 as u16),
Specification = 0x02b0 | (FormKind::Ref as u16),
StartScope = 0x02c0 | (FormKind::Data4 as u16),
StrideSize = 0x02e0 | (FormKind::Data4 as u16),
UpperBoundRef = 0x02f0 | (FormKind::Ref as u16),
UpperBoundData2 = 0x02f0 | (FormKind::Data2 as u16),
UpperBoundData4 = 0x02f0 | (FormKind::Data4 as u16),
UpperBoundData8 = 0x02f0 | (FormKind::Data8 as u16),
Virtual = 0x0300 | (FormKind::String as u16),
VirtualBlock2 = 0x0300 | (FormKind::Block2 as u16),
LoUser = 0x2000,
HiUser = 0x3ff0,
// User types
MwMangled = 0x2000 | (FormKind::String as u16),
MwRestoreSp = 0x2010 | (FormKind::Block2 as u16),
MwGlobalRef = 0x2020 | (FormKind::Ref as u16),
MwGlobalRefByName = 0x2030 | (FormKind::String as u16),
MwRestoreS0 = 0x2040 | (FormKind::Block2 as u16),
MwRestoreS1 = 0x2050 | (FormKind::Block2 as u16),
MwRestoreS2 = 0x2060 | (FormKind::Block2 as u16),
MwRestoreS3 = 0x2070 | (FormKind::Block2 as u16),
MwRestoreS4 = 0x2080 | (FormKind::Block2 as u16),
MwRestoreS5 = 0x2090 | (FormKind::Block2 as u16),
MwRestoreS6 = 0x20A0 | (FormKind::Block2 as u16),
MwRestoreS7 = 0x20B0 | (FormKind::Block2 as u16),
MwRestoreS8 = 0x20C0 | (FormKind::Block2 as u16),
MwRestoreF20 = 0x20D0 | (FormKind::Block2 as u16),
MwRestoreF21 = 0x20E0 | (FormKind::Block2 as u16),
MwRestoreF22 = 0x20F0 | (FormKind::Block2 as u16),
MwRestoreF23 = 0x2100 | (FormKind::Block2 as u16),
MwRestoreF24 = 0x2110 | (FormKind::Block2 as u16),
MwRestoreF25 = 0x2120 | (FormKind::Block2 as u16),
MwRestoreF26 = 0x2130 | (FormKind::Block2 as u16),
MwRestoreF27 = 0x2140 | (FormKind::Block2 as u16),
MwRestoreF28 = 0x2150 | (FormKind::Block2 as u16),
MwRestoreF29 = 0x2160 | (FormKind::Block2 as u16),
MwRestoreF30 = 0x2170 | (FormKind::Block2 as u16),
MwRestoreD20 = 0x2180 | (FormKind::Block2 as u16),
MwRestoreD21 = 0x2190 | (FormKind::Block2 as u16),
MwRestoreD22 = 0x21A0 | (FormKind::Block2 as u16),
MwRestoreD23 = 0x21B0 | (FormKind::Block2 as u16),
MwRestoreD24 = 0x21C0 | (FormKind::Block2 as u16),
MwRestoreD25 = 0x21D0 | (FormKind::Block2 as u16),
MwRestoreD26 = 0x2240 | (FormKind::Block2 as u16),
MwRestoreD27 = 0x2250 | (FormKind::Block2 as u16),
MwRestoreD28 = 0x2260 | (FormKind::Block2 as u16),
MwRestoreD29 = 0x2270 | (FormKind::Block2 as u16),
MwRestoreD30 = 0x2280 | (FormKind::Block2 as u16),
MwOverlayId = 0x2290 | (FormKind::Data4 as u16),
MwOverlayName = 0x22A0 | (FormKind::String as u16),
MwGlobalRefsBlock = 0x2300 | (FormKind::Block2 as u16),
MwLocalSpoffset = 0x2310 | (FormKind::Block4 as u16),
MwMips16 = 0x2330 | (FormKind::String as u16),
MwDwarf2Location = 0x2340 | (FormKind::Block2 as u16),
GccSfName = 0x8000 | (FormKind::Data4 as u16), // GccSfName extension (offset into .debug_sfnames)
GccSfInfo = 0x8010 | (FormKind::Data4 as u16), // GccSfInfo extension (offset into .debug_srcinfo)
MwPrologueEnd = 0x8040 | (FormKind::Addr as u16),
MwEpilogueStart = 0x8050 | (FormKind::Addr as u16),
}
#[derive(Debug, Clone)]
pub enum AttributeValue {
Address(u32),
Reference(u32),
Data2(u16),
Data4(u32),
Data8(u64),
Block(Vec<u8>),
String(String),
}
#[derive(Debug, Clone)]
pub struct Attribute {
pub kind: AttributeKind,
pub value: AttributeValue,
}
#[derive(Debug, Clone)]
pub struct Tag {
pub key: u32,
pub kind: TagKind,
pub is_erased: bool, // Tag was deleted but has been reconstructed
pub is_erased_root: bool, // Tag is erased and is the root of a tree of erased tags
pub data_endian: Endian, // Endianness of the tag data (could be different from the address endianness for erased tags)
pub attributes: Vec<Attribute>,
}
pub type TagMap = BTreeMap<u32, Tag>;
pub type TypedefMap = BTreeMap<u32, Vec<u32>>;
pub type MemberFunctionMap = BTreeMap<u32, BTreeSet<u32>>;
#[derive(Debug, Clone)]
pub struct DwarfInfo {
pub e: Endian,
pub tags: TagMap,
pub producer: Producer,
pub member_functions: RefCell<MemberFunctionMap>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Producer {
MWCC,
GCC,
OTHER,
}
impl Tag {
#[inline]
pub fn attribute(&self, kind: AttributeKind) -> Option<&Attribute> {
self.attributes.iter().find(|attr| attr.kind == kind)
}
#[inline]
pub fn address_attribute(&self, kind: AttributeKind) -> Option<u32> {
match self.attribute(kind) {
Some(Attribute { value: AttributeValue::Address(addr), .. }) => Some(*addr),
_ => None,
}
}
#[inline]
pub fn reference_attribute(&self, kind: AttributeKind) -> Option<u32> {
match self.attribute(kind) {
Some(Attribute { value: AttributeValue::Reference(addr), .. }) => Some(*addr),
_ => None,
}
}
#[inline]
pub fn string_attribute(&self, kind: AttributeKind) -> Option<&String> {
match self.attribute(kind) {
Some(Attribute { value: AttributeValue::String(str), .. }) => Some(str),
_ => None,
}
}
#[inline]
pub fn block_attribute(&self, kind: AttributeKind) -> Option<&[u8]> {
match self.attribute(kind) {
Some(Attribute { value: AttributeValue::Block(vec), .. }) => Some(vec),
_ => None,
}
}
#[inline]
pub fn data4_attribute(&self, kind: AttributeKind) -> Option<u32> {
match self.attribute(kind) {
Some(Attribute { value: AttributeValue::Data4(value), .. }) => Some(*value),
_ => None,
}
}
#[inline]
pub fn data2_attribute(&self, kind: AttributeKind) -> Option<u16> {
match self.attribute(kind) {
Some(Attribute { value: AttributeValue::Data2(value), .. }) => Some(*value),
_ => None,
}
}
#[inline]
pub fn type_attribute(&self) -> Option<&Attribute> {
self.attributes.iter().find(|attr| {
matches!(
attr.kind,
AttributeKind::FundType
| AttributeKind::ModFundType
| AttributeKind::UserDefType
| AttributeKind::ModUDType
)
})
}
pub fn children<'a>(&self, tags: &'a TagMap) -> Vec<&'a Tag> {
let sibling = self.next_sibling(tags);
let mut children = Vec::new();
let mut child = match self.next_tag(tags, self.is_erased) {
Some(child) => child,
None => return children,
};
loop {
if let Some(end) = sibling {
if child.key == end.key {
break;
}
}
if child.kind != TagKind::Padding {
children.push(child);
}
match child.next_sibling(tags) {
Some(next) => child = next,
None => break,
}
}
children
}
/// Returns the next sibling tag, if any
pub fn next_sibling<'a>(&self, tags: &'a TagMap) -> Option<&'a Tag> {
if let Some(key) = self.reference_attribute(AttributeKind::Sibling) {
tags.get(&key)
} else {
self.next_tag(tags, self.is_erased)
}
}
/// Returns the next tag sequentially, if any (skipping erased tags)
pub fn next_tag<'a>(&self, tags: &'a TagMap, include_erased: bool) -> Option<&'a Tag> {
tags.range(self.key + 1..)
.find(|(_, tag)| include_erased || !tag.is_erased)
.map(|(_, tag)| tag)
}
}
pub fn read_debug_section<R>(reader: &mut R, e: Endian, include_erased: bool) -> Result<DwarfInfo>
where R: BufRead + Seek + ?Sized {
let len = {
let old_pos = reader.stream_position()?;
let len = reader.seek(SeekFrom::End(0))?;
reader.seek(SeekFrom::Start(old_pos))?;
len
};
let mut info = DwarfInfo {
e,
tags: BTreeMap::new(),
producer: Producer::OTHER,
member_functions: RefCell::new(MemberFunctionMap::new()),
};
loop {
let position = reader.stream_position()?;
if position >= len {
break;
}
let tags = read_tags(reader, e, e, include_erased, false)?;
for tag in tags {
info.tags.insert(tag.key, tag);
}
}
Ok(info)
}
pub fn parse_producer(producer: &str) -> Producer {
match producer {
p if p.starts_with("MW") => Producer::MWCC,
p if p.starts_with("GNU C") => Producer::GCC,
_ => Producer::OTHER,
}
}
#[allow(unused)]
pub fn read_aranges_section<R>(reader: &mut R, e: Endian) -> Result<()>
where R: BufRead + Seek + ?Sized {
let len = {
let old_pos = reader.stream_position()?;
let len = reader.seek(SeekFrom::End(0))?;
reader.seek(SeekFrom::Start(old_pos))?;
len
};
// let mut tags = BTreeMap::new();
loop {
let position = reader.stream_position()?;
if position >= len {
break;
}
let size = u32::from_reader(reader, e)?;
let version = u8::from_reader(reader, e)?;
ensure!(version == 1, "Expected version 1, got {version}");
let _debug_offs = u32::from_reader(reader, e)?;
let _debug_size = u32::from_reader(reader, e)?;
while reader.stream_position()? < position + size as u64 {
let _address = u32::from_reader(reader, e)?;
let _length = u32::from_reader(reader, e)?;
}
}
Ok(())
}
fn read_tags<R>(
reader: &mut R,
data_endian: Endian,
addr_endian: Endian,
include_erased: bool,
is_erased: bool,
) -> Result<Vec<Tag>>
where
R: BufRead + Seek + ?Sized,
{
let mut tags = Vec::new();
let position = reader.stream_position()?;
let size = u32::from_reader(reader, data_endian)?;
if size < 8 {
// Null entry
if size > 4 {
reader.seek(SeekFrom::Current(size as i64 - 4))?;
}
tags.push(Tag {
key: position as u32,
kind: TagKind::Padding,
is_erased,
is_erased_root: false,
data_endian,
attributes: Vec::new(),
});
return Ok(tags);
}
let tag_num = u16::from_reader(reader, data_endian)?;
let tag = TagKind::try_from(tag_num).context("Unknown DWARF tag type")?;
if tag == TagKind::Padding {
if include_erased {
// Erased entries that have become padding could be either
// little-endian or big-endian, and we have to guess the length and
// tag of the first entry. We assume the entry is either a variable
// or a function, and read until we find the high_pc attribute. Only
// MwGlobalRef will follow, and these are unlikely to be confused
// with the length of the next entry.
let mut attributes = Vec::new();
let mut is_function = false;
// Guess endianness based on first attribute
let data_endian = if is_erased {
data_endian
} else {
// Peek next two bytes
let mut buf = [0u8; 2];
reader.read_exact(&mut buf)?;
let attr_tag = u16::from_reader(&mut Cursor::new(&buf), data_endian)?;
reader.seek(SeekFrom::Current(-2))?;
match AttributeKind::try_from(attr_tag) {
Ok(_) => data_endian,
Err(_) => data_endian.flip(),
}
};
while reader.stream_position()? < position + size as u64 {
// Peek next two bytes
let mut buf = [0u8; 2];
reader.read_exact(&mut buf)?;
let attr_tag = u16::from_reader(&mut Cursor::new(&buf), data_endian)?;
reader.seek(SeekFrom::Current(-2))?;
if is_function && attr_tag != AttributeKind::MwGlobalRef as u16 {
break;
}
let attr = read_attribute(reader, data_endian, addr_endian)?;
if attr.kind == AttributeKind::HighPc {
is_function = true;
}
attributes.push(attr);
}
let kind = if is_function { TagKind::Subroutine } else { TagKind::LocalVariable };
tags.push(Tag {
key: position as u32,
kind,
is_erased: true,
is_erased_root: true,
data_endian,
attributes,
});
// Read the rest of the tags
while reader.stream_position()? < position + size as u64 {
for tag in read_tags(reader, data_endian, addr_endian, include_erased, true)? {
tags.push(tag);
}
}
} else {
reader.seek(SeekFrom::Start(position + size as u64))?; // Skip padding
}
} else {
let mut attributes = Vec::new();
while reader.stream_position()? < position + size as u64 {
attributes.push(read_attribute(reader, data_endian, addr_endian)?);
}
tags.push(Tag {
key: position as u32,
kind: tag,
is_erased,
is_erased_root: false,
data_endian,
attributes,
});
}
Ok(tags)
}
// TODO Shift-JIS?
fn read_string<R>(reader: &mut R) -> Result<String>
where R: BufRead + ?Sized {
let mut str = String::new();
let mut buf = [0u8; 1];
loop {
reader.read_exact(&mut buf)?;
if buf[0] == 0 {
break;
}
str.push(buf[0] as char);
}
Ok(str)
}
fn read_attribute<R>(
reader: &mut R,
data_endian: Endian,
addr_endian: Endian,
) -> Result<Attribute>
where
R: BufRead + Seek + ?Sized,
{
let attr_type = u16::from_reader(reader, data_endian)?;
let attr = AttributeKind::try_from(attr_type).context("Unknown DWARF attribute type")?;
let form = FormKind::try_from(attr_type & FORM_MASK).context("Unknown DWARF form type")?;
let value = match form {
FormKind::Addr => AttributeValue::Address(u32::from_reader(reader, addr_endian)?),
FormKind::Ref => AttributeValue::Reference(u32::from_reader(reader, addr_endian)?),
FormKind::Block2 => {
let size = u16::from_reader(reader, data_endian)?;
let mut data = vec![0u8; size as usize];
reader.read_exact(&mut data)?;
AttributeValue::Block(data)
}
FormKind::Block4 => {
let size = u32::from_reader(reader, data_endian)?;
let mut data = vec![0u8; size as usize];
reader.read_exact(&mut data)?;
AttributeValue::Block(data)
}
FormKind::Data2 => AttributeValue::Data2(u16::from_reader(reader, data_endian)?),
FormKind::Data4 => AttributeValue::Data4(u32::from_reader(reader, data_endian)?),
FormKind::Data8 => AttributeValue::Data8(u64::from_reader(reader, data_endian)?),
FormKind::String => AttributeValue::String(read_string(reader)?),
};
Ok(Attribute { kind: attr, value })
}
#[derive(Debug, Clone)]
pub struct ArrayDimension {
pub index_type: Type,
pub size: Option<NonZeroU32>,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u16)]
pub enum ArrayOrdering {
RowMajor = 0,
// ORD_row_major
ColMajor = 1, // ORD_col_major
}
#[derive(Debug, Clone)]
pub struct ArrayType {
pub element_type: Box<Type>,
pub dimensions: Vec<ArrayDimension>,
}
#[derive(Debug, Clone)]
pub struct BitData {
pub bit_size: u32,
pub bit_offset: u16,
}
#[derive(Debug, Clone)]
pub struct StructureMember {
pub name: Option<String>,
pub kind: Type,
pub offset: u32,
pub bit: Option<BitData>,
pub visibility: Visibility,
pub byte_size: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructureKind {
Struct,
Class,
}
#[derive(Debug, Clone)]
pub struct StructureType {
pub kind: StructureKind,
pub name: Option<String>,
pub byte_size: Option<u32>,
pub member_functions: Vec<MemberSubroutineDefType>,
pub members: Vec<StructureMember>,
pub static_members: Vec<VariableTag>,
pub bases: Vec<StructureBase>,
pub inner_types: Vec<UserDefinedType>,
pub typedefs: Vec<TypedefTag>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
Private,
Protected,
Public,
}
#[derive(Debug, Clone)]
pub struct StructureBase {
pub name: Option<String>,
pub base_type: Type,
pub offset: u32,
pub visibility: Option<Visibility>,
pub virtual_base: bool,
}
#[derive(Debug, Clone)]
pub struct EnumerationMember {
pub name: String,
pub value: i32,
}
#[derive(Debug, Clone)]
pub struct EnumerationType {
pub name: Option<String>,
pub byte_size: u32,
pub members: Vec<EnumerationMember>,
}
#[derive(Debug, Clone)]
pub struct UnionType {
pub name: Option<String>,
pub byte_size: u32,
pub members: Vec<StructureMember>,
}
#[derive(Debug, Clone)]
pub struct SubroutineParameter {
pub name: Option<String>,
pub kind: Type,
pub location: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SubroutineVariable {
pub name: Option<String>,
pub mangled_name: Option<String>,
pub kind: Type,
pub location: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SubroutineLabel {
pub name: String,
pub address: u32,
}
#[derive(Debug, Clone)]
pub struct SubroutineBlock {
pub name: Option<String>,
pub start_address: Option<u32>,
pub end_address: Option<u32>,
pub variables: Vec<SubroutineVariable>,
pub blocks_and_inlines: Vec<SubroutineNode>,
pub inner_types: Vec<UserDefinedType>,
pub typedefs: Vec<TypedefTag>,
}
#[derive(Debug, Clone)]
pub enum SubroutineNode {
Block(SubroutineBlock),
Inline(SubroutineType),
}
#[derive(Debug, Clone)]
pub struct MemberSubroutineDefType {
pub name: Option<String>,
pub mangled_name: Option<String>,
pub return_type: Type,
pub parameters: Vec<SubroutineParameter>,
pub var_args: bool,
pub prototyped: bool,
pub member_of: Option<u32>,
pub direct_member_of: Option<u32>,
pub inline: bool,
pub virtual_: bool,
pub local: bool,
pub start_address: Option<u32>,
pub end_address: Option<u32>,
pub const_: bool,
pub static_member: bool,
pub override_: bool,
pub volatile_: bool,
}
#[derive(Debug, Clone)]
pub struct SubroutineType {
pub name: Option<String>,
pub mangled_name: Option<String>,
pub return_type: Type,
pub parameters: Vec<SubroutineParameter>,
pub var_args: bool,
pub prototyped: bool,
pub references: Vec<u32>,
pub member_of: Option<u32>,
pub direct_member_of: Option<u32>,
pub variables: Vec<SubroutineVariable>,
pub inline: bool,
pub virtual_: bool,
pub local: bool,
pub labels: Vec<SubroutineLabel>,
pub blocks_and_inlines: Vec<SubroutineNode>,
pub inner_types: Vec<UserDefinedType>,
pub typedefs: Vec<TypedefTag>,
pub start_address: Option<u32>,
pub end_address: Option<u32>,
pub const_: bool,
pub static_member: bool,
pub override_: bool,
pub volatile_: bool,
}
#[derive(Debug, Clone)]
pub struct PtrToMemberType {
pub kind: Type,
pub containing_type: u32,
}
#[derive(Debug, Clone)]
pub enum UserDefinedType {
Array(ArrayType),
Structure(StructureType),
Enumeration(EnumerationType),
Union(UnionType),
Subroutine(SubroutineType),
PtrToMember(PtrToMemberType),
}
#[derive(Debug, Clone)]
pub struct VariableTag {
pub name: Option<String>,
pub mangled_name: Option<String>,
pub kind: Type,
pub address: Option<u32>,
pub local: bool,
}
#[derive(Debug, Clone)]
pub struct TypedefTag {
pub name: String,
pub kind: Type,
}
#[derive(Debug, Clone)]
pub enum TagType {
Variable(VariableTag),
Typedef(TypedefTag),
UserDefined(Box<UserDefinedType>),
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, IntoPrimitive, TryFromPrimitive)]
#[repr(u32)]
pub enum Language {
C89 = 0x1,
C = 0x2,
Ada83 = 0x3,
CPlusPlus = 0x4,
Cobol74 = 0x5,
Cobol85 = 0x6,
Fortran77 = 0x7,
Fortran90 = 0x8,
Pascal83 = 0x9,
Modula2 = 0xa,
// MWCC asm extension, emitted by PS2 MWCC asm_r5900_elf.dll
MwAsm = 0x8000,
}
impl Display for Language {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Language::C89 => write!(f, "C89"),
Language::C => write!(f, "C"),
Language::Ada83 => write!(f, "Ada83"),
Language::CPlusPlus => write!(f, "C++"),
Language::Cobol74 => write!(f, "Cobol74"),
Language::Cobol85 => write!(f, "Cobol85"),
Language::Fortran77 => write!(f, "Fortran77"),
Language::Fortran90 => write!(f, "Fortran90"),
Language::Pascal83 => write!(f, "Pascal83"),
Language::Modula2 => write!(f, "Modula2"),
Language::MwAsm => write!(f, "MwAsm"),
}
}
}
#[derive(Debug, Clone)]
pub struct CompileUnit {
pub name: String,
pub producer: Option<String>,
pub comp_dir: Option<String>,
pub language: Option<Language>,
pub start_address: Option<u32>,
pub end_address: Option<u32>,
pub gcc_srcfile_name_offset: Option<u32>,
pub gcc_srcinfo_offset: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct OverlayBranch {
pub name: String,
pub id: u32,
pub start_address: u32,
pub end_address: u32,
pub compile_unit: Option<u32>,
}
impl UserDefinedType {
pub fn name(&self) -> Option<String> {
match self {
UserDefinedType::Array(_) | UserDefinedType::PtrToMember(_) => None,
UserDefinedType::Structure(t) => t.name.clone(),
UserDefinedType::Enumeration(t) => t.name.clone(),
UserDefinedType::Union(t) => t.name.clone(),
UserDefinedType::Subroutine(t) => t.name.clone(),
}
}