ms_pdb/
syms.rs

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
//! Decodes symbols records. Reads the "Global Symbols" stream and per-module symbol streams.
//!
//! # References
//!
//! * [`cvinfo.h`](https://github.com/microsoft/microsoft-pdb/blob/805655a28bd8198004be2ac27e6e0290121a5e89/include/cvinfo.h)
//! * [CodeView Symbols](https://llvm.org/docs/PDB/CodeViewSymbols.html)

pub mod builder;
mod iter;
mod kind;
mod offset_segment;

#[doc(inline)]
pub use self::{iter::*, kind::SymKind, offset_segment::*};

use crate::parser::{Number, Parse, Parser, ParserError, ParserMut};
use crate::types::{ItemId, ItemIdLe, TypeIndex, TypeIndexLe};
use bstr::BStr;
use std::fmt::Debug;
use std::mem::size_of;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned, I32, LE, U16, U32};

/// Identifies the kind of symbol streams. Some behaviors of symbol streams are different,
/// depending on which one is being processed.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum SymbolStreamKind {
    /// The Global Symbol Stream
    Global,

    /// A Module Symbol Stream
    Module,
}

impl SymbolStreamKind {
    /// The byte offset within a stream where the symbol records begin.
    pub fn stream_offset(self) -> usize {
        match self {
            Self::Global => 0,
            Self::Module => 4,
        }
    }
}

/// This header is shared by many records that can start a symbol scope.
#[derive(IntoBytes, FromBytes, Unaligned, Immutable, KnownLayout, Default, Clone, Debug)]
#[repr(C)]
#[allow(missing_docs)]
pub struct BlockHeader {
    /// If the record containing this `BlockHeader` is a top-level symbol record (not nested within
    /// another symbol), then this value is 0.
    ///
    /// If the record containing this `BlockHeader` is nested within another symbol, then this
    /// value is the offset in the symbol stream of the parent record.
    pub p_parent: U32<LE>,

    /// Offset in symbol stream of the `P_END` which terminates this block scope.
    pub p_end: U32<LE>,
}

/// Used for the header of S_LPROC32 and S_GPROC32.
///
/// See `PROCSYM32` in `cvinfo.h`.
#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Unaligned, Debug)]
#[repr(C)]
#[allow(missing_docs)]
pub struct ProcFixed {
    pub p_parent: U32<LE>,
    pub p_end: U32<LE>,
    pub p_next: U32<LE>,
    pub proc_len: U32<LE>,
    pub debug_start: U32<LE>,
    pub debug_end: U32<LE>,
    pub proc_type: TypeIndexLe,
    pub offset_segment: OffsetSegment,
    pub flags: u8,
}

/// Used for `S_LPROC32` and `S_GPROC32`.
///
/// These records are found in Module Symbol Streams. They are very important; they describe the
/// beginning of a function (procedure), and they contain other symbols recursively (are a
/// "symbol scope"). The end of the sequence is terminated with an `S_END` symbol.
///
/// This is equivalent to the `PROCSYM32` type defined in `cvinfo.h`. This symbol begins with a
/// `BLOCKSYM` header
///
/// # References
/// * See `PROCSYM32` in `cvinfo.h`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct Proc<'a> {
    pub fixed: &'a ProcFixed,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for Proc<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

// Basic framing and decoding test
#[test]
fn test_parse_proc() {
    #[rustfmt::skip]
    let data = &[
        /* 0x0000 */ 0x2e, 0, 0x10, 0x11,       // size and S_GPROC32
        /* 0x0004 */ 0, 0, 0, 0,                // p_parent
        /* 0x0008 */ 0x40, 0, 0, 0,             // p_end
        /* 0x000c */ 0, 0, 0, 0,                // p_next
        /* 0x0010 */ 42, 0, 0, 0,               // proc_len
        /* 0x0014 */ 10, 0, 0, 0,               // debug_start
        /* 0x0018 */ 20, 0, 0, 0,               // debug_end
        /* 0x001c */ 0xee, 0x10, 0, 0,          // proc_type
        /* 0x0020 */ 0xcc, 0x1, 0, 0,           // offset
        /* 0x0024 */ 1, 0, 0x50, b'm',          // segment, flags, beginning of name
        /* 0x0028 */ b'e', b'm', b's', b'e',    // name
        /* 0x002c */ b't', 0, 0xf1, 0xf2,       // end and padding
        /* 0x0030 */ 2, 0, 6, 0                 // size = 2 and S_END
        /* 0x0034 */
    ];

    let mut i = SymIter::new(data);

    let s0 = i.next().unwrap();
    assert_eq!(s0.kind, SymKind::S_GPROC32);
    assert_eq!(s0.data.len(), 0x2c);

    match s0.parse().unwrap() {
        SymData::Proc(proc) => {
            assert_eq!(proc.fixed.p_parent.get(), 0);
            assert_eq!(proc.fixed.p_end.get(), 0x40);
            assert_eq!(proc.name, "memset");
        }
        _ => panic!(),
    }

    let s1 = i.next().unwrap();
    assert_eq!(s1.kind, SymKind::S_END);
    assert!(s1.data.is_empty());
}

/// `S_GMANPROC`, `S_LMANPROC` - Managed Procedure Start
///
/// See `MANPROCSYM` in `cvinfo.h`.
#[derive(IntoBytes, FromBytes, Immutable, KnownLayout, Unaligned, Debug)]
#[repr(C)]
#[allow(missing_docs)]
pub struct ManagedProcFixed {
    pub p_parent: U32<LE>,
    pub p_end: U32<LE>,
    pub p_next: U32<LE>,
    pub proc_len: U32<LE>,
    pub debug_start: U32<LE>,
    pub debug_end: U32<LE>,
    pub token: U32<LE>,
    pub offset_segment: OffsetSegment,
    pub flags: u8,
    pub return_reg: U16<LE>,
}

/// `S_GMANPROC`, `S_LMANPROC` - Managed Procedure Start
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct ManagedProc<'a> {
    pub fixed: &'a ManagedProcFixed,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for ManagedProc<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Clone, Default)]
#[allow(missing_docs)]
pub struct ThunkFixed {
    pub block: BlockHeader,
    pub p_next: U32<LE>,
    pub offset_segment: OffsetSegment,
    pub length: U16<LE>,
    pub thunk_ordinal: u8,
    // name: strz
    // variant: [u8]
}

#[allow(missing_docs)]
pub struct Thunk<'a> {
    pub fixed: &'a ThunkFixed,
    pub name: &'a BStr,
    pub variant: &'a [u8],
}

impl<'a> Parse<'a> for Thunk<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
            variant: p.take_rest(),
        })
    }
}

/// Describes the start of every symbol record.
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Clone, Default)]
pub struct SymHeader {
    /// The length in bytes of the record.
    ///
    /// This length _does not_ count the length itself, but _does_ count the `kind` that follows it.
    /// Therefore, all well-formed symbol records have `len >= 2`.
    pub len: U16<LE>,

    /// The kind of the symbol.  See `SymKind`.
    pub kind: U16<LE>,
}

/// Points to one symbol record in memory and gives its kind.
#[derive(Clone)]
pub struct Sym<'a> {
    /// The kind of the symbol.
    pub kind: SymKind,
    /// The contents of the record. This slice does _not_ include the `len` or `kind` fields.
    pub data: &'a [u8],
}

impl<'a> Sym<'a> {
    /// Parse the payload of the symbol.
    pub fn parse(&self) -> Result<SymData<'a>, ParserError> {
        SymData::parse(self.kind, self.data)
    }
}

impl<'a> Debug for Sym<'a> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{:?}", self.kind)
    }
}

/// Points to one symbol record in memory and gives its kind. Allows mutation of the contents of
/// the symbol record.
pub struct SymMut<'a> {
    /// The kind of the symbol.
    pub kind: SymKind,
    /// The contents of the record. This slice does _not_ include the `len` or `kind` fields.
    pub data: &'a mut [u8],
}

/// PUBSYM32
///
/// ```text
/// typedef struct PUBSYM32 {
///     unsigned short  reclen;     // Record length
///     unsigned short  rectyp;     // S_PUB32
///     CV_PUBSYMFLAGS  pubsymflags;
///     CV_uoff32_t     off;
///     unsigned short  seg;
///     unsigned char   name[1];    // Length-prefixed name
/// } PUBSYM32;
/// ```
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct Pub<'a> {
    pub fixed: &'a PubFixed,
    pub name: &'a BStr,
}

impl<'a> Pub<'a> {
    /// Gets the `segment:offset` of this symbol.
    pub fn offset_segment(&self) -> OffsetSegment {
        self.fixed.offset_segment.clone()
    }
}

#[allow(missing_docs)]
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct PubFixed {
    pub flags: U32<LE>,
    pub offset_segment: OffsetSegment,
    // name: &str
}

#[allow(missing_docs)]
impl<'a> Parse<'a> for Pub<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

impl<'a> Pub<'a> {
    /// Parses `S_PUB32_ST`
    pub fn parse_st(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strt_raw()?,
        })
    }
}

/// Parsed form of `S_CONSTANT`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct Constant<'a> {
    pub type_: TypeIndex,
    pub value: Number<'a>,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for Constant<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            type_: p.type_index()?,
            value: p.number()?,
            name: p.strz()?,
        })
    }
}

/// Parsed form of `S_CONSTANT`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct ManagedConstant<'a> {
    pub token: u32,
    pub value: Number<'a>,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for ManagedConstant<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            token: p.u32()?,
            value: p.number()?,
            name: p.strz()?,
        })
    }
}

/// Several symbols use this structure: `S_PROCREF`, `S_LPROCREF`, `S_DATAREF`. These symbols
/// are present in the Global Symbol Stream, not in module symbol streams.
///
/// These `S_*REF` symbols tell you where to find a specific global symbol, but they do not directly
/// describe the symbol. Instead, you have to load the corresponding module
///
///
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct RefSym2<'a> {
    pub header: &'a RefSym2Fixed,
    pub name: &'a BStr,
}

#[allow(missing_docs)]
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct RefSym2Fixed {
    /// Checksum of the name (called `SUC` in C++ code)
    ///
    /// This appears to be set to zero.
    pub name_checksum: U32<LE>,

    /// Offset of actual symbol in $$Symbols
    ///
    /// This is the byte offset into the module symbol stream for this symbol. The `module_index`
    /// field tells you which symbol stream to load, to resolve this value.
    pub symbol_offset: U32<LE>,

    /// The 1-based index of the module containing the actual symbol.
    ///
    /// This value is 1-based. Subtract 1 from this value before indexing into a zero-based module array.
    pub module_index: U16<LE>,
    // pub name: strz, // hidden name made a first class member
}

impl<'a> Parse<'a> for RefSym2<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            header: p.get()?,
            name: p.strz()?,
        })
    }
}

#[allow(missing_docs)]
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct ThreadStorageFixed {
    pub type_: TypeIndexLe,
    pub offset_segment: OffsetSegment,
}

/// Record data for `S_LTHREAD32` and `S_GTHREAD32`. These describes thread-local storage.
///
/// Thread-local storage is declared using `__declspec(thread)` or `thread_static`, in C++.
#[derive(Clone, Debug)]
pub struct ThreadStorageData<'a> {
    #[allow(missing_docs)]
    pub header: &'a ThreadStorageFixed,
    #[allow(missing_docs)]
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for ThreadStorageData<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            header: p.get()?,
            name: p.strz()?,
        })
    }
}

#[allow(missing_docs)]
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct DataFixed {
    pub type_: TypeIndexLe,
    pub offset_segment: OffsetSegment,
}

/// Record data for `S_LDATA32` and `S_GDATA32`. These describe global storage.
#[allow(missing_docs)]
#[derive(Clone)]
pub struct Data<'a> {
    pub header: &'a DataFixed,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for Data<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            header: p.get()?,
            name: p.strz()?,
        })
    }
}

impl<'a> Debug for Data<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Data: {} {:?} {}",
            self.header.offset_segment,
            self.header.type_.get(),
            self.name
        )
    }
}

/// Record data for `S_UDT` symbols
#[derive(Clone, Debug)]
pub struct Udt<'a> {
    /// The type of the UDT
    pub type_: TypeIndex,
    /// Name
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for Udt<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            type_: p.type_index()?,
            name: p.strz()?,
        })
    }
}

/// `S_OBJNAME`
#[derive(Clone, Debug)]
pub struct ObjectName<'a> {
    /// A robust signature that will change every time that the module will be compiled or
    /// different in any way. It should be at least a CRC32 based upon module name and contents.
    pub signature: u32,
    /// Full path of the object file.
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for ObjectName<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            signature: p.u32()?,
            name: p.strz()?,
        })
    }
}

/// `S_COMPILE3`
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[repr(C)]
#[allow(missing_docs)]
pub struct Compile3Fixed {
    pub flags: U32<LE>,
    pub machine: U16<LE>,
    pub frontend_major: U16<LE>,
    pub frontend_minor: U16<LE>,
    pub frontend_build: U16<LE>,
    pub frontend_qfe: U16<LE>,
    pub ver_major: U16<LE>,
    pub ver_minor: U16<LE>,
    pub ver_build: U16<LE>,
    pub ver_qfe: U16<LE>,
    // name: strz
}

/// `S_COMPILE3`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct Compile3<'a> {
    pub fixed: &'a Compile3Fixed,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for Compile3<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

/// `S_FRAMEPROC`: This symbol is used for indicating a variety of extra information regarding a
/// procedure and its stack frame. If any of the flags are non-zero, this record should be added
/// to the symbols for that procedure.
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct FrameProc {
    /// Count of bytes in the whole stack frame.
    frame_size: U32<LE>,
    /// Count of bytes in the frame allocated as padding.
    pad_size: U32<LE>,
    /// Offset of pad bytes from the base of the frame.
    pad_offset: U32<LE>,
    /// Count of bytes in frame allocated for saved callee-save registers.
    save_regs_size: U32<LE>,
    offset_exception_handler: U32<LE>,
    exception_handler_section: U16<LE>,
    padding: U16<LE>,
    flags: U32<LE>,
}

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct RegRelFixed {
    pub offset: U32<LE>,
    pub ty: TypeIndexLe,
    pub register: U16<LE>,
    // name: strz
}

/// `S_REGREGL32`: This symbol specifies symbols that are allocated relative to a register.
/// This should be used on all platforms besides x86 and on x86 when the register is not a form of EBP.
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct RegRel<'a> {
    pub fixed: &'a RegRelFixed,
    pub name: &'a BStr,
}

impl<'a> Parse<'a> for RegRel<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

/// Block Start: This symbol specifies the start of an inner block of lexically scoped symbols.
/// The lexical scope is terminated by a matching `S_END` symbol.
///
/// This symbol should only be nested (directly or indirectly) within a function symbol
/// (`S_GPROC32`, `S_LPROC32`, etc.).
///
/// See `BLOCKSYM32`
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct Block<'a> {
    pub fixed: &'a BlockFixed,
    pub name: &'a BStr,
}

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct BlockFixed {
    /// Header of the block
    pub header: BlockHeader,

    /// Length in bytes of the scope of this block within the executable code stream.
    pub length: U32<LE>,

    pub offset_segment: OffsetSegment,
}

impl<'a> Parse<'a> for Block<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

/// Local Symbol: This symbol defines a local variable.
///
/// This symbol must be nested (directly or indirectly) within a function symbol. It must be
/// followed by more range descriptions.
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct Local<'a> {
    pub fixed: &'a LocalFixed,
    pub name: &'a BStr,
}

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct LocalFixed {
    pub ty: TypeIndexLe,
    /// The spec says this is a 32-bit flags field, but the actual records show that this is 16-bit.
    pub flags: U16<LE>,
    // name: strz
}

impl<'a> Parse<'a> for Local<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

/// Represents an address range, used for optimized code debug info
///
/// See `CV_LVAR_ADDR_RANGE`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct LVarAddrRange {
    /// Start of the address range
    pub start: OffsetSegment,
    /// Size of the range in bytes.
    pub range_size: U16<LE>,
}

/// Represents the holes in overall address range, all address is pre-bbt.
/// it is for compress and reduce the amount of relocations need.
///
/// See `CV_LVAR_ADDR_GAP`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct LVarAddrGap {
    /// relative offset from the beginning of the live range.
    pub gap_start_offset: U16<LE>,
    /// length of this gap, in bytes
    pub range_size: U16<LE>,
}

/// `S_DEFRANGE_FRAMEPOINTER_REL`: A live range of frame variable
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct DefRangeSymFramePointerRelFixed {
    pub offset_to_frame_pointer: U32<LE>,

    /// Range of addresses where this program is valid
    pub range: LVarAddrRange,
}

/// `S_DEFRANGE_FRAMEPOINTER_REL`: A live range of frame variable
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct DefRangeSymFramePointerRel<'a> {
    pub fixed: &'a DefRangeSymFramePointerRelFixed,
    // The value is not available in following gaps.
    pub gaps: &'a [LVarAddrGap],
}

impl<'a> Parse<'a> for DefRangeSymFramePointerRel<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        let fixed = p.get()?;
        let gaps = p.slice(p.len() / size_of::<LVarAddrGap>())?;
        Ok(Self { fixed, gaps })
    }
}

/// Attributes for a register range
///
/// See `CV_RANGEATTR`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct RangeAttrLe {
    // unsigned short  maybe : 1;    // May have no user name on one of control flow path.
    // unsigned short  padding : 15; // Padding for future use.
    pub value: U16<LE>,
}

/// `S_DEFRANGE_REGISTER` - A live range of en-registed variable
///
/// See `DEFRANGESYMREGISTER`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct DefRangeRegisterFixed {
    /// Register to hold the value of the symbol
    pub reg: U16<LE>,
    // Attribute of the register range.
    pub attr: RangeAttrLe,
}

/// `S_DEFRANGE_REGISTER`
///
/// See `DEFRANGESYMREGISTER`
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct DefRangeRegister<'a> {
    pub fixed: &'a DefRangeRegisterFixed,
    pub gaps: &'a [u8],
}

impl<'a> Parse<'a> for DefRangeRegister<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            gaps: p.take_rest(),
        })
    }
}

/// `S_DEFRANGE_REGISTER_REL`
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct DefRangeRegisterRel<'a> {
    pub fixed: &'a DefRangeRegisterRelFixed,

    /// The value is not available in following gaps.
    pub gaps: &'a [u8],
}

/// `S_DEFRANGE_REGISTER_REL`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
pub struct DefRangeRegisterRelFixed {
    /// Register to hold the base pointer of the symbol
    pub base_reg: U16<LE>,

    /// ```text
    /// unsigned short  spilledUdtMember : 1;   // Spilled member for s.i.
    /// unsigned short  padding          : 3;   // Padding for future use.
    /// unsigned short  offsetParent     : CV_OFFSET_PARENT_LENGTH_LIMIT;  // Offset in parent variable.
    /// ```
    pub flags: U16<LE>,

    /// offset to register
    pub base_pointer_offset: I32<LE>,

    /// Range of addresses where this program is valid
    pub range: LVarAddrRange,
}

impl<'a> Parse<'a> for DefRangeRegisterRel<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            gaps: p.take_rest(),
        })
    }
}

/// `S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE`
///
/// A frame variable valid in all function scope.
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Clone, Debug)]
#[repr(C)]
pub struct DefRangeFramePointerRelFullScope {
    /// offset to frame pointer
    pub frame_pointer_offset: I32<LE>,
}

/// `S_DEFRANGE_SUBFIELD_REGISTER`
///
/// See `DEFRANGESYMSUBFIELDREGISTER`
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct DefRangeSubFieldRegister<'a> {
    pub fixed: &'a DefRangeSubFieldRegisterFixed,
    pub gaps: &'a [u8],
}

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct DefRangeSubFieldRegisterFixed {
    pub reg: U16<LE>,
    pub attr: RangeAttrLe,
    pub flags: U32<LE>,
    pub range: LVarAddrRange,
}

impl<'a> Parse<'a> for DefRangeSubFieldRegister<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            gaps: p.take_rest(),
        })
    }
}

/// `S_GMANPROC`, `S_LMANPROC`, `S_GMANPROCIA64`, `S_LMANPROCIAC64`
///
/// See `MANPROCSYM`
pub struct ManProcSym<'a> {
    #[allow(missing_docs)]
    pub fixed: &'a ManProcSymFixed,
    #[allow(missing_docs)]
    pub name: &'a BStr,
}

/// MSIL / CIL token value
pub type TokenIdLe = U32<LE>;

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct ManProcSymFixed {
    pub block: BlockHeader,
    /// pointer to next symbol
    pub pnext: U32<LE>,
    /// Proc length
    pub len: U32<LE>,
    /// Debug start offset
    pub dbg_start: U32<LE>,
    /// Debug end offset
    pub dbg_end: U32<LE>,
    // COM+ metadata token for method
    pub token: TokenIdLe,
    pub off: U32<LE>,
    pub seg: U16<LE>,
    pub flags: u8, // CV_PROCFLAGS: Proc flags
    pub padding: u8,
    // Register return value is in (may not be used for all archs)
    pub ret_reg: U16<LE>,
    // name: strz    // optional name field
}

impl<'a> Parse<'a> for ManProcSym<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

/// `S_TRAMPOLINE`
#[derive(Clone, Debug)]
pub struct Trampoline<'a> {
    /// Fixed header
    pub fixed: &'a TrampolineFixed,

    /// Data whose interpretation depends on `tramp_type`
    pub rest: &'a [u8],
}

/// `S_TRAMPOLINE`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Clone, Debug)]
pub struct TrampolineFixed {
    /// trampoline sym subtype
    pub tramp_type: U16<LE>,
    /// size of the thunk
    pub cb_thunk: U16<LE>,
    /// offset of the thunk
    pub off_thunk: U32<LE>,
    /// offset of the target of the thunk
    pub off_target: U32<LE>,
    /// section index of the thunk
    pub sect_thunk: U16<LE>,
    /// section index of the target of the thunk
    pub sect_target: U16<LE>,
}

impl<'a> Parse<'a> for Trampoline<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            rest: p.take_rest(),
        })
    }
}

/// `S_BUILDINFO` - Build info for a module
///
/// This record is present only in module symbol streams.
#[derive(Clone, Debug)]
pub struct BuildInfo {
    /// ItemId points to an `LF_BUILDINFO` record in IPI
    pub item: ItemId,
}

impl<'a> Parse<'a> for BuildInfo {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self { item: p.u32()? })
    }
}

/// `S_UNAMESPACE` - Using Namespace
#[derive(Clone, Debug)]
pub struct UsingNamespace<'a> {
    /// The namespace, e.g. `std`
    pub namespace: &'a BStr,
}

impl<'a> Parse<'a> for UsingNamespace<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            namespace: p.strz()?,
        })
    }
}

/// `S_LABEL32`
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct Label<'a> {
    pub fixed: &'a LabelFixed,
    pub name: &'a BStr,
}

/// `S_LABEL32`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct LabelFixed {
    pub offset_segment: OffsetSegment,
    pub flags: u8,
}

impl<'a> Parse<'a> for Label<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            name: p.strz()?,
        })
    }
}

/// `S_CALLERS` or `S_CALLEES`
#[derive(Clone, Debug)]
pub struct FunctionList<'a> {
    /// The list of functions, in the IPI. Each is either `LF_FUNC_ID` or `LF_MFUNC_ID`.
    pub funcs: &'a [ItemIdLe],

    /// Invocation counts. The items in `invocations` parallel the items in `funcs`, but the length
    /// of `invocations` can be less than the length of `funcs`. Unmatched functions are assumed
    /// to have an invocation count of zero.
    pub invocations: &'a [U32<LE>],
}

impl<'a> Parse<'a> for FunctionList<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        let count = p.u32()?;
        let funcs: &[ItemIdLe] = p.slice(count as usize)?;
        let num_invocations = p.len() / size_of::<U32<LE>>();
        let invocations = p.slice(num_invocations)?;
        Ok(Self { funcs, invocations })
    }
}

/// `S_INLINESITE`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct InlineSite<'a> {
    pub fixed: &'a InlineSiteFixed,
    /// an array of compressed binary annotations.
    pub binary_annotations: &'a [u8],
}

/// `S_INLINESITE`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct InlineSiteFixed {
    pub block: BlockHeader,
    pub inlinee: ItemIdLe,
}

impl<'a> Parse<'a> for InlineSite<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            binary_annotations: p.take_rest(),
        })
    }
}

/// `S_INLINESITE2`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct InlineSite2<'a> {
    pub fixed: &'a InlineSite2Fixed,
    /// an array of compressed binary annotations.
    pub binary_annotations: &'a [u8],
}

/// `S_INLINESITE`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct InlineSite2Fixed {
    pub block: BlockHeader,
    pub inlinee: ItemIdLe,
    pub invocations: U32<LE>,
}

impl<'a> Parse<'a> for InlineSite2<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            binary_annotations: p.take_rest(),
        })
    }
}

/// `S_FRAMECOOKIE`: Symbol for describing security cookie's position and type
// (raw, xor'd with esp, xor'd with ebp).
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct FrameCookie {
    /// Frame relative offset
    pub offset: I32<LE>,
    pub reg: U16<LE>,
    pub cookie_type: u8,
    pub flags: u8,
}

/// `S_CALLSITEINFO`
///
/// Symbol for describing indirect calls when they are using
/// a function pointer cast on some other type or temporary.
/// Typical content will be an LF_POINTER to an LF_PROCEDURE
/// type record that should mimic an actual variable with the
/// function pointer type in question.
///
/// Since the compiler can sometimes tail-merge a function call
/// through a function pointer, there may be more than one
/// S_CALLSITEINFO record at an address.  This is similar to what
/// you could do in your own code by:
///
/// ```text
///  if (expr)
///      pfn = &function1;
///  else
///      pfn = &function2;
///
///  (*pfn)(arg list);
/// ```
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct CallSiteInfo {
    pub offset: OffsetSegment,
    pub padding: U16<LE>,
    pub func_type: TypeIndexLe,
}

/// `S_HEAPALLOCSITE`
#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct HeapAllocSite {
    pub offset: OffsetSegment,
    /// length of heap allocation call instruction
    pub instruction_size: U16<LE>,
    pub func_type: TypeIndexLe,
}

/// `S_ANNOTATION`
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct Annotation<'a> {
    pub fixed: &'a AnnotationFixed,
    pub strings: &'a [u8],
}

#[repr(C)]
#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Unaligned, Debug)]
#[allow(missing_docs)]
pub struct AnnotationFixed {
    pub offset: OffsetSegment,
    pub num_strings: U16<LE>,
}

impl<'a> Parse<'a> for Annotation<'a> {
    fn from_parser(p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(Self {
            fixed: p.get()?,
            strings: p.take_rest(),
        })
    }
}

impl<'a> Annotation<'a> {
    /// Iterates the strings stored in the annotation.
    pub fn iter_strings(&self) -> AnnotationIterStrings<'a> {
        AnnotationIterStrings {
            num_strings: self.fixed.num_strings.get(),
            bytes: self.strings,
        }
    }
}

/// Iterator state for [`Annotation::iter_strings`].
#[allow(missing_docs)]
pub struct AnnotationIterStrings<'a> {
    pub num_strings: u16,
    pub bytes: &'a [u8],
}

impl<'a> Iterator for AnnotationIterStrings<'a> {
    type Item = &'a BStr;

    fn next(&mut self) -> Option<Self::Item> {
        if self.num_strings == 0 {
            return None;
        }

        self.num_strings -= 1;
        let mut p = Parser::new(self.bytes);
        let s = p.strz().ok()?;
        self.bytes = p.into_rest();
        Some(s)
    }
}

// Trampoline subtypes

/// Incremental thunks
pub const TRAMPOLINE_KIND_INCREMENTAL: u16 = 0;
/// Branch island thunks
pub const TRAMPOLINE_KIND_BRANCH_ISLAND: u16 = 1;

/// Parsed data from a symbol record
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub enum SymData<'a> {
    Unknown,
    ObjName(ObjectName<'a>),
    Compile3(Compile3<'a>),
    Proc(Proc<'a>),
    Udt(Udt<'a>),
    Constant(Constant<'a>),
    ManagedConstant(ManagedConstant<'a>),
    RefSym2(RefSym2<'a>),
    Data(Data<'a>),
    ThreadData(ThreadStorageData<'a>),
    Pub(Pub<'a>),
    End,
    FrameProc(&'a FrameProc),
    RegRel(RegRel<'a>),
    Block(Block<'a>),
    Local(Local<'a>),
    DefRangeFramePointerRel(DefRangeSymFramePointerRel<'a>),
    DefRangeRegister(DefRangeRegister<'a>),
    DefRangeRegisterRel(DefRangeRegisterRel<'a>),
    DefRangeFramePointerRelFullScope(&'a DefRangeFramePointerRelFullScope),
    DefRangeSubFieldRegister(DefRangeSubFieldRegister<'a>),
    Trampoline(Trampoline<'a>),
    BuildInfo(BuildInfo),
    UsingNamespace(UsingNamespace<'a>),
    InlineSiteEnd,
    Label(Label<'a>),
    FunctionList(FunctionList<'a>),
    InlineSite(InlineSite<'a>),
    InlineSite2(InlineSite2<'a>),
    FrameCookie(&'a FrameCookie),
    CallSiteInfo(&'a CallSiteInfo),
    HeapAllocSite(&'a HeapAllocSite),
    ManagedProc(ManagedProc<'a>),
    Annotation(Annotation<'a>),
}

impl<'a> SymData<'a> {
    /// Parses a symbol record. The caller has already parsed the length and kind of the record.
    /// The `data` parameter does not include the length or kind.
    pub fn parse(kind: SymKind, data: &'a [u8]) -> Result<Self, ParserError> {
        let mut p = Parser::new(data);
        Self::from_parser(kind, &mut p)
    }

    /// Parses a symbol record. The caller has already parsed the length and kind of the record.
    /// The `p` parameter does not include the length or kind.
    ///
    /// This function allows the caller to observe how many bytes were actually consumed from
    /// the input stream.
    pub fn from_parser(kind: SymKind, p: &mut Parser<'a>) -> Result<Self, ParserError> {
        Ok(match kind {
            SymKind::S_OBJNAME => Self::ObjName(p.parse()?),
            SymKind::S_GPROC32 | SymKind::S_LPROC32 => Self::Proc(p.parse()?),
            SymKind::S_COMPILE3 => Self::Compile3(p.parse()?),
            SymKind::S_UDT => Self::Udt(p.parse()?),
            SymKind::S_CONSTANT => Self::Constant(p.parse()?),
            SymKind::S_MANCONSTANT => Self::Constant(p.parse()?),
            SymKind::S_PUB32 => Self::Pub(p.parse()?),
            SymKind::S_PUB32_ST => Self::Pub(Pub::parse_st(p)?),

            SymKind::S_PROCREF
            | SymKind::S_LPROCREF
            | SymKind::S_DATAREF
            | SymKind::S_ANNOTATIONREF => Self::RefSym2(p.parse()?),

            SymKind::S_LDATA32 | SymKind::S_GDATA32 | SymKind::S_LMANDATA | SymKind::S_GMANDATA => {
                Self::Data(p.parse()?)
            }

            SymKind::S_LTHREAD32 | SymKind::S_GTHREAD32 => Self::ThreadData(p.parse()?),
            SymKind::S_END => Self::End,
            SymKind::S_FRAMEPROC => Self::FrameProc(p.get()?),
            SymKind::S_REGREL32 => Self::RegRel(p.parse()?),
            SymKind::S_BLOCK32 => Self::Block(p.parse()?),
            SymKind::S_LOCAL => Self::Local(p.parse()?),
            SymKind::S_DEFRANGE_FRAMEPOINTER_REL => Self::DefRangeFramePointerRel(p.parse()?),
            SymKind::S_DEFRANGE_REGISTER => Self::DefRangeRegister(p.parse()?),
            SymKind::S_DEFRANGE_REGISTER_REL => Self::DefRangeRegisterRel(p.parse()?),
            SymKind::S_DEFRANGE_FRAMEPOINTER_REL_FULL_SCOPE => {
                Self::DefRangeFramePointerRelFullScope(p.get()?)
            }
            SymKind::S_DEFRANGE_SUBFIELD_REGISTER => Self::DefRangeSubFieldRegister(p.parse()?),
            SymKind::S_TRAMPOLINE => Self::Trampoline(p.parse()?),
            SymKind::S_BUILDINFO => Self::BuildInfo(p.parse()?),
            SymKind::S_UNAMESPACE => Self::UsingNamespace(p.parse()?),
            SymKind::S_INLINESITE_END => Self::InlineSiteEnd,
            SymKind::S_LABEL32 => Self::Label(p.parse()?),
            SymKind::S_CALLEES | SymKind::S_CALLERS => Self::FunctionList(p.parse()?),
            SymKind::S_INLINESITE => Self::InlineSite(p.parse()?),
            SymKind::S_INLINESITE2 => Self::InlineSite2(p.parse()?),
            SymKind::S_INLINEES => Self::FunctionList(p.parse()?),
            SymKind::S_FRAMECOOKIE => Self::FrameCookie(p.get()?),
            SymKind::S_CALLSITEINFO => Self::CallSiteInfo(p.get()?),
            SymKind::S_HEAPALLOCSITE => Self::HeapAllocSite(p.get()?),
            SymKind::S_GMANPROC | SymKind::S_LMANPROC => Self::ManagedProc(p.parse()?),
            SymKind::S_ANNOTATION => Self::Annotation(p.parse()?),

            _ => Self::Unknown,
        })
    }

    /// If this symbol record has a "name" field, return it. Else, `None`.
    pub fn name(&self) -> Option<&'a BStr> {
        match self {
            Self::Proc(proc) => Some(proc.name),
            Self::Data(data) => Some(data.name),
            Self::ThreadData(thread_data) => Some(thread_data.name),
            Self::Udt(udt) => Some(udt.name),
            Self::Local(local) => Some(local.name),
            Self::RefSym2(refsym) => Some(refsym.name),
            Self::Constant(c) => Some(c.name),
            Self::ManagedConstant(c) => Some(c.name),
            _ => None,
        }
    }
}