btf-rs 2.0.0

Library for the BPF type format (BTF).
Documentation
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
//! Main object of the `btf-rs` crate, providing a way to parse BTF data and
//! helpers to query the information it describes.

use std::{
    convert::AsRef,
    fs::File,
    io::{BufReader, Cursor, Read},
    path::Path,
    sync::Arc,
};

use fallible_iterator::FallibleIterator;
use memmap2::MmapOptions;

use crate::{cbtf, section::BtfSection, Error, Result};

/// Backend used by the [`Btf`] object to store and access the underlying BTF
/// information.
#[non_exhaustive]
pub enum Backend {
    /// Parse the BTF data during initialization and then store the result. This
    /// provides faster API calls at the cost of a slower initialization and
    /// larger memory footprint.
    Cache,
    /// Mmap the BTF data without parsing all of it. This provides a smaller
    /// memory footprint and faster initialization at the cost of slower API
    /// calls.
    Mmap,
}

/// Main representation of parsed BTF data. Provides helpers to resolve types
/// and their associated names.
pub struct Btf {
    obj: Arc<BtfSection>,
    base: Option<Arc<BtfSection>>,
}

impl Btf {
    /// Parse a stand-alone BTF section from a file and construct a Rust
    /// representation for later use. By default [`Backend::Cache`] is used.
    ///
    /// Trying to open split BTF files using this function will fail. For split
    /// BTF files use [`Btf::from_split_file`].
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::from_file_with_backend(&path, Backend::Cache)
    }

    /// Same as [`Btf::from_file`] but forcing a given [`Backend`] to be used.
    /// This allows selecting the desired behavior and balance, but can fail if
    /// a given [`Backend`] isn't supported by the underlying system.
    pub fn from_file_with_backend<P: AsRef<Path>>(path: P, backend: Backend) -> Result<Self> {
        Ok(Btf {
            obj: Arc::new(match backend {
                Backend::Cache => {
                    BtfSection::from_reader(&mut BufReader::new(File::open(path)?), None)?
                }
                Backend::Mmap => BtfSection::from_mmap(
                    unsafe { MmapOptions::new().map_copy_read_only(&File::open(path)?)? },
                    None,
                )?,
            }),
            base: None,
        })
    }

    /// Parse a split BTF section from a file and construct a Rust
    /// representation for later use. A base [`Btf`] containing the base section
    /// must be provided.
    pub fn from_split_file<P: AsRef<Path>>(path: P, base: &Btf) -> Result<Btf> {
        if base.base.is_some() {
            return Err(Error::OpNotSupp("Provided base is a split BTF".to_string()));
        }

        Ok(Btf {
            obj: Arc::new(BtfSection::from_reader(
                &mut BufReader::new(File::open(path)?),
                Some(base.obj.clone()),
            )?),
            base: Some(base.obj.clone()),
        })
    }

    /// Perform the same actions as [`Btf::from_file`], but fed with a byte
    /// slice.
    pub fn from_bytes(bytes: &[u8]) -> Result<Btf> {
        Ok(Btf {
            obj: Arc::new(BtfSection::from_reader(&mut Cursor::new(bytes), None)?),
            base: None,
        })
    }

    /// Performs the same actions as [`Btf::from_split_file`], but fed with a
    /// byte slice.
    pub fn from_split_bytes(bytes: &[u8], base: &Btf) -> Result<Btf> {
        if base.base.is_some() {
            return Err(Error::OpNotSupp("Provided base is a split BTF".to_string()));
        }

        let base = base.obj.clone();
        Ok(Btf {
            obj: Arc::new(BtfSection::from_reader(
                &mut Cursor::new(bytes),
                Some(base.clone()),
            )?),
            base: Some(base),
        })
    }

    /// Returns a reference the base BTF section. For non-split `Btf` the base
    /// BTF section holds the full BTF representation. Base BTF sections are
    /// standalone representations (no reference to external BTF sections).
    pub fn base(&self) -> &BtfSection {
        match &self.base {
            Some(base) => base,
            None => &self.obj,
        }
    }

    /// Returns a reference to the split BTF section, if any. A split BTF
    /// section is not a standalone representation (it uses references to a base
    /// BTF section).
    pub fn split(&self) -> Option<&BtfSection> {
        self.base.as_ref()?;
        Some(&self.obj)
    }

    /// Find a list of BTF ids with a given name.
    ///
    /// Using an empty name (`""`) resolves anonymous ids.
    pub fn resolve_ids_by_name(&self, name: &str) -> Result<Vec<u32>> {
        let mut ids = self.obj.resolve_ids_by_name(name)?;

        if let Some(base) = &self.base {
            ids.append(&mut base.resolve_ids_by_name(name)?);
        }

        Ok(ids)
    }

    /// Find a list of BTF ids whose names match a regex.
    ///
    /// If the regex matches the empty name (`""`), e.g. `"^$"`, the result will
    /// contain anonymous ids.
    #[cfg(feature = "regex")]
    pub fn resolve_ids_by_regex(&self, re: &regex::Regex) -> Result<Vec<u32>> {
        let mut ids = self.obj.resolve_ids_by_regex(re)?;

        if let Some(base) = &self.base {
            ids.append(&mut base.resolve_ids_by_regex(re)?);
        }

        Ok(ids)
    }

    /// Find a BTF type with a given id.
    pub fn resolve_type_by_id(&self, id: u32) -> Result<Type> {
        if let Some(base) = &self.base {
            if let Ok(r#type) = base.resolve_type_by_id(id) {
                return Ok(r#type);
            }
        }

        self.obj.resolve_type_by_id(id)
    }

    /// Find a list of BTF types with a given name.
    ///
    /// Using an empty name (`""`) resolves anonymous types.
    pub fn resolve_types_by_name(&self, name: &str) -> Result<Vec<Type>> {
        let mut types = self.obj.resolve_types_by_name(name)?;

        if let Some(base) = &self.base {
            types.append(&mut base.resolve_types_by_name(name)?);
        }

        Ok(types)
    }

    /// Find a list of BTF types whose names match a regex.
    ///
    /// If the regex matches the empty name (`""`), e.g. `"^$"`, the result will
    /// contain anonymous types.
    #[cfg(feature = "regex")]
    pub fn resolve_types_by_regex(&self, re: &regex::Regex) -> Result<Vec<Type>> {
        let mut types = self.obj.resolve_types_by_regex(re)?;

        if let Some(base) = &self.base {
            types.append(&mut base.resolve_types_by_regex(re)?);
        }

        Ok(types)
    }

    /// Resolve a name referenced by a Type which is defined in the current
    /// [`Btf`] object.
    pub fn resolve_name(&self, r#type: &dyn BtfType) -> Result<String> {
        match &self.base {
            Some(base) => base
                .resolve_name(r#type)
                .or_else(|_| self.obj.resolve_name(r#type)),
            None => self.obj.resolve_name(r#type),
        }
    }

    /// Return an iterator over all types defined in the current BTF object.
    pub fn type_iter(&self) -> TypeIter<'_> {
        TypeIter::new(&self.obj, self.base.as_ref().map(|s| s.as_ref()))
    }

    /// Types can have a reference to another one, e.g. `Ptr -> Int`. This
    /// helper resolve a Type referenced in an other one. It is the main helper
    /// to traverse the Type tree.
    pub fn resolve_chained_type<T: BtfType + ?Sized>(&self, r#type: &T) -> Result<Type> {
        let id = r#type
            .get_type_id()
            .ok_or(Error::OpNotSupp("No chained type in type".to_string()))?;
        self.resolve_type_by_id(id)
    }

    /// This helper returns an iterator that allow to resolve a Type
    /// referenced in another one all the way down to the chain.
    /// The helper makes use of [`Btf::resolve_chained_type`].
    pub fn chained_type_iter<T: BtfType + ?Sized>(&self, r#type: &T) -> ChainedTypeIter<'_> {
        ChainedTypeIter {
            btf: self,
            r#type: self.resolve_chained_type(r#type).ok(),
        }
    }
}

/// Iterator over BTF types.
pub struct TypeIter<'a> {
    pub(crate) section: &'a BtfSection,
    pub(crate) next_section: Option<&'a BtfSection>,
    cursor: u32,
    end: u32,
}

impl<'a> TypeIter<'a> {
    pub(crate) fn new(section: &'a BtfSection, next_section: Option<&'a BtfSection>) -> Self {
        let (start, end) = section.type_id_range();

        TypeIter {
            section,
            next_section,
            cursor: start,
            end,
        }
    }
}

impl FallibleIterator for TypeIter<'_> {
    type Item = Type;
    type Error = Error;

    fn next(&mut self) -> Result<Option<Self::Item>> {
        // Go to the next section if needed.
        if self.cursor > self.end {
            self.section = match self.next_section.take() {
                Some(section) => section,
                None => return Ok(None),
            };

            (self.cursor, self.end) = self.section.type_id_range();
        }

        let r#type = self.section.resolve_type_by_id(self.cursor)?;
        self.cursor += 1;

        Ok(Some(r#type))
    }
}

/// Iterator over chained types (types referencing other types in a chain).
pub struct ChainedTypeIter<'a> {
    btf: &'a Btf,
    r#type: Option<Type>,
}

impl Iterator for ChainedTypeIter<'_> {
    type Item = Type;

    fn next(&mut self) -> Option<Self::Item> {
        match self.r#type.clone() {
            None => None,
            Some(ty) => {
                self.r#type = match ty.as_btf_type() {
                    Some(x) => self.btf.resolve_chained_type(x).ok(),
                    // We might have encountered Void or other
                    // non-BtfType types.
                    None => None,
                };
                Some(ty)
            }
        }
    }
}

/// Rust representation of BTF types. Each type then contains its own specific
/// data and provides helpers to access it.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Type {
    Void,
    Int(Int),
    Ptr(Ptr),
    Array(Array),
    Struct(Struct),
    Union(Union),
    Enum(Enum),
    Fwd(Fwd),
    Typedef(Typedef),
    Volatile(Volatile),
    Const(Const),
    Restrict(Restrict),
    Func(Func),
    FuncProto(FuncProto),
    Var(Var),
    Datasec(Datasec),
    Float(Float),
    DeclTag(DeclTag),
    TypeTag(TypeTag),
    Enum64(Enum64),
}

impl Type {
    // Creates a new Type reading a BTF definition from a reader.
    pub(super) fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        bt: cbtf::btf_type,
    ) -> Result<Self> {
        // Each BTF type needs specific handling to parse its type-specific header.
        use cbtf::BtfKind;
        Ok(match BtfKind::from_id(bt.kind())? {
            BtfKind::Int => Type::Int(Int::from_reader(reader, endianness, bt)?),
            BtfKind::Ptr => Type::Ptr(Ptr::new(bt)),
            BtfKind::Array => Type::Array(Array::from_reader(reader, endianness, bt)?),
            BtfKind::Struct => Type::Struct(Struct::from_reader(reader, endianness, bt)?),
            BtfKind::Union => Type::Union(Struct::from_reader(reader, endianness, bt)?),
            BtfKind::Enum => Type::Enum(Enum::from_reader(reader, endianness, bt)?),
            BtfKind::Fwd => Type::Fwd(Fwd::new(bt)),
            BtfKind::Typedef => Type::Typedef(Typedef::new(bt)),
            BtfKind::Volatile => Type::Volatile(Volatile::new(bt)),
            BtfKind::Const => Type::Const(Volatile::new(bt)),
            BtfKind::Restrict => Type::Restrict(Volatile::new(bt)),
            BtfKind::Func => Type::Func(Func::new(bt)),
            BtfKind::FuncProto => Type::FuncProto(FuncProto::from_reader(reader, endianness, bt)?),
            BtfKind::Var => Type::Var(Var::from_reader(reader, endianness, bt)?),
            BtfKind::Datasec => Type::Datasec(Datasec::from_reader(reader, endianness, bt)?),
            BtfKind::Float => Type::Float(Float::new(bt)),
            BtfKind::DeclTag => Type::DeclTag(DeclTag::from_reader(reader, endianness, bt)?),
            BtfKind::TypeTag => Type::TypeTag(TypeTag::new(bt)),
            BtfKind::Enum64 => Type::Enum64(Enum64::from_reader(reader, endianness, bt)?),
        })
    }

    // Creates a new Type reading a BTF definition from bytes.
    pub(crate) fn from_bytes(
        buf: &[u8],
        endianness: &cbtf::Endianness,
        bt: cbtf::btf_type,
    ) -> Result<Self> {
        Self::from_reader(&mut Cursor::new(buf), endianness, bt)
    }

    /// Returns an `str` representation of the [`Type`].
    pub fn name(&self) -> &'static str {
        match &self {
            Type::Void => "void",
            Type::Int(_) => "int",
            Type::Ptr(_) => "ptr",
            Type::Array(_) => "array",
            Type::Struct(_) => "struct",
            Type::Union(_) => "union",
            Type::Enum(_) => "enum",
            Type::Fwd(_) => "fwd",
            Type::Typedef(_) => "typedef",
            Type::Volatile(_) => "volatile",
            Type::Const(_) => "const",
            Type::Restrict(_) => "restrict",
            Type::Func(_) => "func",
            Type::FuncProto(_) => "func-proto",
            Type::Var(_) => "var",
            Type::Datasec(_) => "datasec",
            Type::Float(_) => "float",
            Type::DeclTag(_) => "decl-tag",
            Type::TypeTag(_) => "type-tag",
            Type::Enum64(_) => "enum64",
        }
    }

    pub fn as_btf_type(&self) -> Option<&dyn BtfType> {
        match self {
            Type::Int(i) => Some(i),
            Type::Ptr(p) => Some(p),
            Type::Array(a) => Some(a),
            Type::Struct(s) => Some(s),
            Type::Union(u) => Some(u),
            Type::Enum(e) => Some(e),
            Type::Fwd(f) => Some(f),
            Type::Typedef(td) => Some(td),
            Type::Volatile(v) => Some(v),
            Type::Const(c) => Some(c),
            Type::Restrict(r) => Some(r),
            Type::Func(fu) => Some(fu),
            Type::Var(v) => Some(v),
            Type::Datasec(ds) => Some(ds),
            Type::Float(f) => Some(f),
            Type::DeclTag(dt) => Some(dt),
            Type::TypeTag(tt) => Some(tt),
            Type::Enum64(e64) => Some(e64),
            _ => None,
        }
    }
}

/// Helpers common to all BTF types. Ease the use of types.
pub trait BtfType {
    /// Returns the offset of the string associated with the type, if any.
    fn get_name_offset(&self) -> Option<u32> {
        None
    }

    /// Returns the type id associated with the current type, if any.
    fn get_type_id(&self) -> Option<u32> {
        None
    }
}

/// Rust representation for BTF type `BTF_KIND_INT`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Int {
    btf_type: cbtf::btf_type,
    btf_int: cbtf::btf_int,
}

impl Int {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Int> {
        Ok(Int {
            btf_type,
            btf_int: cbtf::btf_int::from_reader(reader, endianness)?,
        })
    }

    pub fn is_signed(&self) -> bool {
        self.btf_int.encoding() & cbtf::BTF_INT_SIGNED == cbtf::BTF_INT_SIGNED
    }

    pub fn is_char(&self) -> bool {
        self.btf_int.encoding() & cbtf::BTF_INT_CHAR == cbtf::BTF_INT_CHAR
    }

    pub fn is_bool(&self) -> bool {
        self.btf_int.encoding() & cbtf::BTF_INT_BOOL == cbtf::BTF_INT_BOOL
    }

    pub fn size(&self) -> usize {
        self.btf_type.size().expect("int should have a size")
    }
}

impl BtfType for Int {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Rust representation for BTF type `BTF_KIND_PTR`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ptr {
    btf_type: cbtf::btf_type,
}

impl Ptr {
    fn new(btf_type: cbtf::btf_type) -> Ptr {
        Ptr { btf_type }
    }
}

impl BtfType for Ptr {
    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_ARRAY`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Array {
    btf_type: cbtf::btf_type,
    btf_array: cbtf::btf_array,
}

#[allow(clippy::len_without_is_empty)]
impl Array {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Array> {
        Ok(Array {
            btf_type,
            btf_array: cbtf::btf_array::from_reader(reader, endianness)?,
        })
    }

    /// Number of elements in the `Array`.
    pub fn len(&self) -> usize {
        self.btf_array.nelems as usize
    }
}

impl BtfType for Array {
    fn get_type_id(&self) -> Option<u32> {
        Some(self.btf_array.r#type)
    }
}

/// Rust representation for BTF type `BTF_KIND_STRUCT`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Struct {
    btf_type: cbtf::btf_type,
    /// The members information. Use `.len()` to count them.
    pub members: Vec<Member>,
}

impl Struct {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Struct> {
        let mut members = Vec::new();

        for _ in 0..btf_type.vlen() {
            members.push(Member::from_reader(
                reader,
                endianness,
                btf_type.kind_flag(),
            )?);
        }

        Ok(Struct { btf_type, members })
    }

    pub fn size(&self) -> usize {
        self.btf_type
            .size()
            .expect("struct and union should have a size")
    }
}

impl BtfType for Struct {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Rust representation for BTF type `BTF_KIND_UNION`.
pub type Union = Struct;

/// Represents a [`Struct`] member.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Member {
    kind_flag: u32,
    btf_member: cbtf::btf_member,
}

impl Member {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        kind_flag: u32,
    ) -> Result<Member> {
        Ok(Member {
            kind_flag,
            btf_member: cbtf::btf_member::from_reader(reader, endianness)?,
        })
    }

    pub fn bit_offset(&self) -> u32 {
        match self.kind_flag {
            1 => self.btf_member.offset & 0xffffff,
            _ => self.btf_member.offset,
        }
    }

    pub fn bitfield_size(&self) -> Option<u32> {
        match self.kind_flag {
            1 => Some(self.btf_member.offset >> 24),
            _ => None,
        }
    }
}

impl BtfType for Member {
    fn get_name_offset(&self) -> Option<u32> {
        Some(self.btf_member.name_off)
    }

    fn get_type_id(&self) -> Option<u32> {
        Some(self.btf_member.r#type)
    }
}

/// Rust representation for BTF type `BTF_KIND_ENUM`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Enum {
    btf_type: cbtf::btf_type,
    /// The enum members information. Use `.len()` to count them.
    pub members: Vec<EnumMember>,
}

#[allow(clippy::len_without_is_empty)]
impl Enum {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Enum> {
        let mut members = Vec::new();

        for _ in 0..btf_type.vlen() {
            members.push(EnumMember::from_reader(reader, endianness)?);
        }

        Ok(Enum { btf_type, members })
    }

    pub fn is_signed(&self) -> bool {
        self.btf_type.kind_flag() == 1
    }

    pub fn size(&self) -> usize {
        self.btf_type.size().expect("enum should have a size")
    }
}

impl BtfType for Enum {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Represents an [`Enum`] member.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EnumMember {
    btf_enum: cbtf::btf_enum,
}

impl EnumMember {
    fn from_reader<R: Read>(reader: &mut R, endianness: &cbtf::Endianness) -> Result<EnumMember> {
        Ok(EnumMember {
            btf_enum: cbtf::btf_enum::from_reader(reader, endianness)?,
        })
    }

    pub fn val(&self) -> u32 {
        self.btf_enum.val
    }
}

impl BtfType for EnumMember {
    fn get_name_offset(&self) -> Option<u32> {
        Some(self.btf_enum.name_off)
    }
}

/// Rust representation for BTF type `BTF_KIND_FWD`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Fwd {
    btf_type: cbtf::btf_type,
}

impl Fwd {
    fn new(btf_type: cbtf::btf_type) -> Fwd {
        Fwd { btf_type }
    }

    /// Tests if the forward declaration is for a struct type.
    pub fn is_struct(&self) -> bool {
        self.btf_type.kind_flag() == 0
    }

    /// Tests if the forward declaration is for a union type.
    pub fn is_union(&self) -> bool {
        self.btf_type.kind_flag() == 1
    }
}

impl BtfType for Fwd {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Rust representation for BTF type `BTF_KIND_TYPEDEF`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Typedef {
    btf_type: cbtf::btf_type,
}

impl Typedef {
    fn new(btf_type: cbtf::btf_type) -> Typedef {
        Typedef { btf_type }
    }
}

impl BtfType for Typedef {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }

    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_VOLATILE`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Volatile {
    btf_type: cbtf::btf_type,
}

impl Volatile {
    fn new(btf_type: cbtf::btf_type) -> Volatile {
        Volatile { btf_type }
    }
}

impl BtfType for Volatile {
    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_CONST`.
pub type Const = Volatile;

/// Rust representation for BTF type `BTF_KIND_RESTRICT`.
pub type Restrict = Volatile;

/// Rust representation for BTF type `BTF_KIND_FUNC`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Func {
    btf_type: cbtf::btf_type,
}

impl Func {
    fn new(btf_type: cbtf::btf_type) -> Func {
        Func { btf_type }
    }

    pub fn is_static(&self) -> bool {
        self.btf_type.vlen() == cbtf::BTF_FUNC_STATIC
    }

    pub fn is_global(&self) -> bool {
        self.btf_type.vlen() == cbtf::BTF_FUNC_GLOBAL
    }

    pub fn is_extern(&self) -> bool {
        self.btf_type.vlen() == cbtf::BTF_FUNC_EXTERN
    }
}

impl BtfType for Func {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }

    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_FUNC_PROTO`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FuncProto {
    btf_type: cbtf::btf_type,
    pub parameters: Vec<Parameter>,
}

impl FuncProto {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<FuncProto> {
        let mut parameters = Vec::new();

        for _ in 0..btf_type.vlen() {
            parameters.push(Parameter::from_reader(reader, endianness)?);
        }

        Ok(FuncProto {
            btf_type,
            parameters,
        })
    }

    pub fn return_type_id(&self) -> u32 {
        self.btf_type
            .r#type()
            .expect("func proto should have a type")
    }
}

/// Represents a [`FuncProto`] parameter.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Parameter {
    btf_param: cbtf::btf_param,
}

impl Parameter {
    fn from_reader<R: Read>(reader: &mut R, endianness: &cbtf::Endianness) -> Result<Parameter> {
        Ok(Parameter {
            btf_param: cbtf::btf_param::from_reader(reader, endianness)?,
        })
    }

    pub fn is_variadic(&self) -> bool {
        self.btf_param.name_off == 0 && self.btf_param.r#type == 0
    }
}

impl BtfType for Parameter {
    fn get_name_offset(&self) -> Option<u32> {
        Some(self.btf_param.name_off)
    }

    fn get_type_id(&self) -> Option<u32> {
        Some(self.btf_param.r#type)
    }
}

/// Rust representation for BTF type `BTF_KIND_VAR`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Var {
    btf_type: cbtf::btf_type,
    btf_var: cbtf::btf_var,
}

impl Var {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Var> {
        Ok(Var {
            btf_type,
            btf_var: cbtf::btf_var::from_reader(reader, endianness)?,
        })
    }

    pub fn is_static(&self) -> bool {
        self.btf_var.linkage == cbtf::BTF_VAR_STATIC
    }

    pub fn is_global(&self) -> bool {
        self.btf_var.linkage == cbtf::BTF_VAR_GLOBAL_ALLOCATED
    }

    pub fn is_extern(&self) -> bool {
        self.btf_var.linkage == cbtf::BTF_VAR_GLOBAL_EXTERN
    }
}

impl BtfType for Var {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }

    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_DATASEC`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Datasec {
    btf_type: cbtf::btf_type,
    pub variables: Vec<VarSecinfo>,
}

impl Datasec {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Datasec> {
        let mut variables = Vec::new();

        for _ in 0..btf_type.vlen() {
            variables.push(VarSecinfo::from_reader(reader, endianness)?);
        }

        Ok(Datasec {
            btf_type,
            variables,
        })
    }

    pub fn size(&self) -> usize {
        self.btf_type.size().expect("datasec should have a size")
    }
}

impl BtfType for Datasec {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Represents a [`Datasec`] variable.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VarSecinfo {
    btf_var_secinfo: cbtf::btf_var_secinfo,
}

impl VarSecinfo {
    fn from_reader<R: Read>(reader: &mut R, endianness: &cbtf::Endianness) -> Result<VarSecinfo> {
        Ok(VarSecinfo {
            btf_var_secinfo: cbtf::btf_var_secinfo::from_reader(reader, endianness)?,
        })
    }

    pub fn offset(&self) -> u32 {
        self.btf_var_secinfo.offset
    }

    pub fn size(&self) -> usize {
        self.btf_var_secinfo.size as usize
    }
}

impl BtfType for VarSecinfo {
    fn get_type_id(&self) -> Option<u32> {
        Some(self.btf_var_secinfo.r#type)
    }
}

/// Rust representation for BTF type `BTF_KIND_FLOAT`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Float {
    btf_type: cbtf::btf_type,
}

impl Float {
    fn new(btf_type: cbtf::btf_type) -> Float {
        Float { btf_type }
    }

    pub fn size(&self) -> usize {
        self.btf_type.size().expect("float should have a size")
    }
}

impl BtfType for Float {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Rust representation for BTF type `BTF_KIND_DECL_TAG`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeclTag {
    btf_type: cbtf::btf_type,
    btf_decl_tag: cbtf::btf_decl_tag,
}

impl DeclTag {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<DeclTag> {
        Ok(DeclTag {
            btf_type,
            btf_decl_tag: cbtf::btf_decl_tag::from_reader(reader, endianness)?,
        })
    }

    pub fn component_index(&self) -> Option<u32> {
        let component_idx = self.btf_decl_tag.component_idx;
        match component_idx {
            x if x < 0 => None,
            x => Some(x as u32),
        }
    }

    pub fn is_attribute(&self) -> bool {
        self.btf_type.kind_flag() == 1
    }
}

impl BtfType for DeclTag {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }

    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_TYPE_TAG`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TypeTag {
    btf_type: cbtf::btf_type,
}

impl TypeTag {
    fn new(btf_type: cbtf::btf_type) -> TypeTag {
        TypeTag { btf_type }
    }

    pub fn is_attribute(&self) -> bool {
        self.btf_type.kind_flag() == 1
    }
}

impl BtfType for TypeTag {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }

    fn get_type_id(&self) -> Option<u32> {
        self.btf_type.r#type()
    }
}

/// Rust representation for BTF type `BTF_KIND_ENUM64`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Enum64 {
    btf_type: cbtf::btf_type,
    /// The enum members information. Use `.len()` to count them.
    pub members: Vec<Enum64Member>,
}

#[allow(clippy::len_without_is_empty)]
impl Enum64 {
    fn from_reader<R: Read>(
        reader: &mut R,
        endianness: &cbtf::Endianness,
        btf_type: cbtf::btf_type,
    ) -> Result<Enum64> {
        let mut members = Vec::new();

        for _ in 0..btf_type.vlen() {
            members.push(Enum64Member::from_reader(reader, endianness)?);
        }

        Ok(Enum64 { btf_type, members })
    }

    pub fn is_signed(&self) -> bool {
        self.btf_type.kind_flag() == 1
    }

    pub fn size(&self) -> usize {
        self.btf_type.size().expect("enum64 should have a size")
    }
}

impl BtfType for Enum64 {
    fn get_name_offset(&self) -> Option<u32> {
        self.btf_type.name_offset()
    }
}

/// Represents an [`Enum64`] member.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Enum64Member {
    btf_enum64: cbtf::btf_enum64,
}

impl Enum64Member {
    fn from_reader<R: Read>(reader: &mut R, endianness: &cbtf::Endianness) -> Result<Enum64Member> {
        Ok(Enum64Member {
            btf_enum64: cbtf::btf_enum64::from_reader(reader, endianness)?,
        })
    }

    pub fn val(&self) -> u64 {
        ((self.btf_enum64.val_hi32 as u64) << 32) | self.btf_enum64.val_lo32 as u64
    }
}

impl BtfType for Enum64Member {
    fn get_name_offset(&self) -> Option<u32> {
        Some(self.btf_enum64.name_off)
    }
}