Skip to main content

sbpf_disassembler/
section_header_entry.rs

1use {
2    crate::errors::DisassemblerError,
3    serde::{Deserialize, Serialize},
4    std::fmt::Debug,
5};
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct SectionHeaderEntry {
9    pub label: String,
10    pub offset: usize,
11    pub data: Vec<u8>,
12    #[serde(skip_serializing_if = "String::is_empty")]
13    pub utf8: String,
14}
15
16impl SectionHeaderEntry {
17    pub fn new(label: String, offset: usize, data: Vec<u8>) -> Result<Self, DisassemblerError> {
18        let mut h = SectionHeaderEntry {
19            label,
20            offset,
21            data,
22            utf8: String::new(),
23        };
24
25        if let Ok(utf8) = String::from_utf8(h.data.clone()) {
26            h.utf8 = utf8;
27        }
28        Ok(h)
29    }
30
31    pub fn offset(&self) -> usize {
32        self.offset
33    }
34
35    pub fn to_bytes(&self) -> Vec<u8> {
36        self.data.clone()
37    }
38}
39
40#[cfg(test)]
41mod test {
42    use {
43        crate::section_header_entry::SectionHeaderEntry,
44        either::Either,
45        sbpf_common::{
46            inst_param::{Number, Register},
47            instruction::Instruction,
48            opcode::Opcode,
49        },
50    };
51
52    #[test]
53    fn serialize_e2e() {
54        let data = vec![
55            0x18, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
56            0x00, 0x00, 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
57        ];
58
59        let h = SectionHeaderEntry::new(".text\0".to_string(), 128, data.clone()).unwrap();
60
61        let ixs = [
62            Instruction {
63                opcode: Opcode::Lddw,
64                dst: Some(Register { n: 1 }),
65                src: None,
66                off: None,
67                imm: Some(Either::Right(Number::Int(0))),
68                span: 0..16,
69            }
70            .to_bytes()
71            .unwrap(),
72            Instruction {
73                opcode: Opcode::Exit,
74                dst: None,
75                src: None,
76                off: None,
77                imm: None,
78                span: 0..8,
79            }
80            .to_bytes()
81            .unwrap(),
82        ]
83        .concat();
84
85        assert_eq!(ixs, h.to_bytes());
86    }
87
88    #[test]
89    fn test_offset() {
90        let data = vec![0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
91        let h = SectionHeaderEntry::new(".test".to_string(), 256, data).unwrap();
92        assert_eq!(h.offset(), 256);
93    }
94}